Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access new props.value before render function in React life cycle

All:

If I define a component have a property called "value",

var Child = React.createClass({
  componentWillReceiveProps: function(){
     console.log("componentWillReceiveProps",this.props.value);
  },
  shouldComponentUpdate : function(){
    console.log("shouldComponentUpdate", this.props.value);
    return true;
  },
  componentWillUpdate : function(){
    console.log("componentWillUpdate", this.props.value);
  },
  componentDidUpdate: function(){
    console.log("componentDidUpdate", this.props.value);
  },
  render: function(){
    return (
      <div>The value generated by Parent: {this.props.value}</div>
    );
  }
});

If I want to give the newly set props.value to state.value( or maybe prepare a value for transition/interpolation ), but all stages before render only have previous value. Could anyone show me how to get new value before render?

Thanks

like image 990
Kuan Avatar asked Jan 08 '23 12:01

Kuan


2 Answers

Important Note: componentWillReceiveProps is deprecated: https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops


componentWillReceiveProps is called when a component receives new props.

From here you can update the component's state using setState without triggering a render.

  1. You can access the new props from the first argument passed to componentWillReceiveProps
  2. You can access the old props this.props

From your example:

componentWillReceiveProps: function(nextProps){
    console.log("componentWillReceiveProps", nextProps.value, this.props.value);
},

JSBin demo

like image 192
Tom Yates Avatar answered Jan 16 '23 02:01

Tom Yates


For anybody finding this old question via Google, it's out of date. You shouldn't be using this function anymore and, moreover, there are other solutions that don't involve updating the state! Take a look at this react.js blog article, You Probably Don't Need Derived State.

It's not totally clear what OP wanted to do but there are various appropriate solutions in that article. In my case, I wanted to reset a popup window, when a different element was clicked. You can do this with the key attribute. It works like magic. :)

like image 36
Matthew Kirschnick Avatar answered Jan 16 '23 02:01

Matthew Kirschnick