1

I use this to method to work with component, the componentWillMount to initialize data for homepage and the componentWillReceiveProps when router change (category page), but when I come back home page from category page, I know because componentWillMount just do one time so I cannot see data.

componentWillMount(){
        this.props.fetchBooks(1)
    }
componentWillReceiveProps(nextProps){
        if(nextProps.match.params.id && nextProps.match.params.id !== this.props.match.params.id){
            this.props.fetchBookByCategory(nextProps.match.params.id)
        } 
    }

I put this initialized code to componentWillReceiveProps, It works but It calls the fetchBooks(1) constantly eventhough I tried to do with some condition, please help me this problems, many thanks.

2 Answers2

0

You have to set nextProps to this.props on componentWillReceiveProps

componentWillReceiveProps(nextProps){
        if(nextProps.match.params.id && nextProps.match.params.id !== this.props.match.params.id){
            this.props.fetchBookByCategory(nextProps.match.params.id)
 this.props = nextProps;
        } 
0

Never do fetching in componentWillMount or the constructor. instead do it in componentDidMount.

componentWillMount:

componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state synchronously in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.

componentDidMount

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.

You can conditionally render your page if data wasn't received yet.

render(){
  return(
    <div>
      {
        data.length > 0 ? 
        <List items={data} /> : 
        <div>Loading...</div>
      }
    </div>
  );
}
Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99
  • Thank you!, with the code I posted, componentDidMount and WillMount call only first time I render homepage, when I change router from other page It cannot show data, I tried re-fetch for home page in componentWillReceiveProps, It works but It fetch Data many, many time, constantly – Cường Nguyễn Oct 02 '17 at 08:14
  • when you re-render your component then `componentDidMount` should be called again. – Sagiv b.g Oct 02 '17 at 08:30