Update state values with props change in reactjs

后端 未结 1 1714
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-14 00:22

I have a modal component that should be called when setState changes but for some reason it is not updating. In the first file Im setting the following in render.

         


        
相关标签:
1条回答
  • 2021-01-14 00:29

    No constructor will not get called when component re-rendered, it will get called only on initial rendering.

    I think, there are two ways by which you can solve your issue:

    1. Use componentWillReceiveProps(){ lifecycle method it will get called whenever any change happens to props values, so you can update the Modal component state value showModal here, like this:

    componentWillReceiveProps(nextProp){
       this.setState({
          show: nextProps.showModal
       });
    }
    

    As per DOC:

    componentWillReceiveProps() is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.

    2. Don't store the props value in state variable and directly use this.props.showModel in Model component, by this way whenever any change happens to props values, Modal component will take the updated values.

    0 讨论(0)
提交回复
热议问题