Tu Le Thanh
Tu Le Thanh

Reputation: 671

React component doesn't re-render after I changed state

I have 2 components: PhotoList and Pagination. Inside PhotoList, I use componentDidMount to call the api from the server based on the currentPage value stored in PhotoList's state.

I also wrote pageChanged method to change currentPage value and passed this method through props for Pagination component

pageChanged = (numPage) => {
    this.setState({
      currentPage: numPage
    });
    // console.log("Day la currentPage hien tai: ",this.state.currentPage);
  }
<Pagination 
            totalPages={Math.floor(this.state.totalImages/30)+1}
            clicked={this.pageChanged}
/>

Inside Pagination component, I called above method like this

<a onClick={(event) => {this.props.clicked(event.target.text)}}>2</a>

So I just updated the currentPage value but my PhotoList component didn't re-render. And another thing is when I click it for the first time, the currentPage value doesn't change (still is 1 default value) until I click it for the second time.

Pls help me. Thanks

Upvotes: 0

Views: 157

Answers (2)

Sourav Singh
Sourav Singh

Reputation: 955

Here is the working example of setstate from one component to another https://jsfiddle.net/singhsourav930/1ctg2k7a/7/

class PhotoList extends React.Component {
  /**
   * State
   */
  state = {
    currentPage: 0,
  };

  /**
   * When component did mount
   * This function trigger only once
   * Here you can set your initial values
   */
  componentDidMount() {
    this.setState({ currentPage: 1 });
  }

  /**
   * Page changed
   * @param {Number} numPage
   */
  pageChanged = (numPage) => {
    this.setState({
      currentPage: numPage,
    });
  };

  /**
   * Render
   */
  render() {
    const { currentPage } = this.state;
    console.log(currentPage);
    return (
      <div>
        <Pagination clicked={this.pageChanged} />
      </div>
    );
  }
}

class Pagination extends React.Component {
  render() {
    const { clicked } = this.props;

    return (
      <div>
        <a onClick={() => clicked(2)}>2</a>
        <br />
        <a onClick={() => clicked(3)}>3</a>
        <br />
        <a onClick={() => clicked(4)}>4</a>
        <br />
        <a onClick={() => clicked(5)}>5</a>
      </div>
    );
  }
}

ReactDOM.render(<PhotoList />, document.getElementById('container'));

Upvotes: 0

Ryuko
Ryuko

Reputation: 377

componentDidMount() is only called once when the component is rendered first time. You should recall the api when the pageChanged is called or after you called setState.

Also, setState is asynchronous, so when you clicked first time, it doesn't log the updated value. For example, you can do like this

pageChanged = (numPage) => {
   this.setState({
      currentPage: numPage
   }, () => { 
      // console.log("Day la currentPage hien tai: ",this.state.currentPage);
      /* YOUR API CALL */ 
   });
}

Upvotes: 1

Related Questions