简体   繁体   中英

State changed in componentWillReceiveProps is not showing up in the render

I have defined a state in my constructor and it's like this

      this.state={
            datainaccordion:'',

        };

Now in my componentWillReceiveProps , I have changed the state everytime we receive new Props and it is like this,

componentWillReceiveProps(nextProps){
        console.log('something',nextProps);
        if (nextProps.data) {
        this.setState({ datainaccordion: nextProps.data });
       }
       console.log('this.state.datainaccordion ',this.state.datainaccordion);
    }

I can see the console and it is working fine every time a new data comes but when I console log the same state inside render I don't see this console. What can be the reason for this and why is it happening? Another thing is that I have put another console.log('rendering') inside my render and even this doesn't show up. How do i make it render everytime I get new data? I am adding the render part too here .

render(){
         console.log('rendering');  // this is not being printed  
        console.log('rung',this.state.datainaccordion);
     // some logic to extract an array out of the data in this .state.datainaccordion and we call it arraytoloop



        return (
            <div>
                     <SomeComponentXYz

                       data={arraytoloop}

                       />
              </div>


       );    }

 }

as @satyajeet jha said

This Component is extended from PureComponent. But PureComponent has implemented shouldComponentUpdate .

React.PureComponent's shouldComponentUpdate() only shallowly compares the objects. ...
Only extend PureComponent when you expect to have simple props and state

and your field datainaccordion is object as I suppose. So shouldComponentUpdate in PureComponent will return false and stop updating because it doesnt check difference between old and new object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM