Dawn17
Dawn17

Reputation: 8297

Rotating 3 pages in React

This is what I've been trying right now, but it keeps rendering the same page after the first switch.

I tried to follow the react lifecycle to figure it out, but it doesn't work as I intended.

I want it to start from RepoPage -> TimerPage -> ClockPage -> RepoPage and so on.

How can I fix it?

EDIT:

const REPO_PAGE = '5_SECONDS';
const COUNTDOWN_PAGE = '15_SECONDS';
const TIME_PAGE = '15_SECONDS';

const RepoComponent = () => (
  <div>REPO</div>
);

const SprintCountComponent = () => (
  <div>TIMER></div>
);

const DateTimeComponent = () => (
  <div>CLOCK</div>
);


class App extends Component {
  constructor(props) {
    super(props);
    this.state = {

      repoTitles: [],
      userData: [],
      commitData: [],
      recentTwoData: [],
      currentPage: REPO_PAGE,
      imgURL: ""

    };

  }

  componentDidUpdate() {
    const {currentPage} = this.state;
    const isRepoPage = currentPage === REPO_PAGE;
    const isTimePage = currentPage === TIME_PAGE;

    if (isRepoPage) {
      this._showDateTimePageDelayed();
    } else if (isTimePage) {
      this._showCountDownPageDelayed();
    } else {
      this._showRepoPageDelayed();
    }
  }

  componentDidMount() {
    this._showCountDownPageDelayed();
  };

  _showCountDownPageDelayed = () => setTimeout(() => {this.setState({currentPage: COUNTDOWN_PAGE})}, 5000);

  _showRepoPageDelayed = () => setTimeout(() => {this.setState({currentPage: REPO_PAGE})}, 5000);

  _showDateTimePageDelayed = () => setTimeout(() => {this.setState({currentPage: TIME_PAGE})}, 5000);

  render() {
    const {currentPage} = this.state;
    const isRepoPage = currentPage === REPO_PAGE;
    const isTimePage = currentPage === TIME_PAGE;

    if(isRepoPage) {
      return <RepoComponent/>;
    } else if(isTimePage) {
      return <DateTimeComponent/>;
    } else {
      return <SprintCountComponent/>;  
    }

  }
}

Upvotes: 0

Views: 27

Answers (1)

Roy Wang
Roy Wang

Reputation: 11260

You did not have return or else so this._showCountDownPageDelayed() is always executed.

if (isRepoPage) {
  this._showDateTimePageDelayed();
} else if(isTimePage) {
  this._showRepoPageDelayed();
} else {
  this._showCountDownPageDelayed();
}

Using setInterval might give you a cleaner solution.

Edit: Your logic causes it to alternate between RepoPage and TimePage. A quick fix would be:

if (isRepoPage) {
  this._showDateTimePageDelayed();
} else if (isTimePage) {
  this._showCountDownPageDelayed();
} else {
  this._showRepoPageDelayed();
}

Upvotes: 1

Related Questions