When to use componentWillReceiveProps lifecycle method?

后端 未结 5 969
时光取名叫无心
时光取名叫无心 2020-12-04 23:51

I am new to React/Redux and have a problem with state.

TrajectContainer.jsx

class TrajectContainer extends React.Component {
    con         


        
5条回答
  •  被撕碎了的回忆
    2020-12-05 00:29

    In your case you will require componentWillReceiveProps and you have to update the state when you receive new props. Because

    • In your constructor, you have declared your state as below. As you can see you construct your state using the props that are passed in. (This is why you require componentWillReceiveProps and the logic to update it there)

      this.state = {
          trajects: props.trajects,
          onClick: props.onClick
      };
      
    • So when your props, changes componentWillReceiveProps is the function that gets called. The constructor does not gets called. So you have to set the state again so that the changes goes into the state of the component.

    • However your logic should be as below. With a condition so that you can prevent repeated state updates if its called multiple times.

      componentWillReceiveProps(nextProps) {
       console.log('componentWillReceiveProps', nextProps);
       if (this.props !== nextProps) {
        this.setState(nextProps);
       }
      }
      

    One should store the props into state, only if you are going to modify the content of it. But in your case i see that there is no modification. So you can directly use this.props.trajects directly instead of storing it into the state and then using it. This way you can get rid of the componentWillReceiveProps So your render function will use something like below

    {this.props.trajects.map(traject => //what ever is your code.... }
    

提交回复
热议问题