Will componentWillRecieveProps run every time props are received

后端 未结 2 698
遇见更好的自我
遇见更好的自我 2021-01-15 01:01

I was reading React facebook\'s documentation and there it is written that

Invoked when a component is receiving new props. This method is not call

相关标签:
2条回答
  • 2021-01-15 01:10

    Initial renders means when your component is loaded first time with whatever data it has. E.g:

    Parent
        constructor() {
                super();
                this.state = {
                    viewData:undefined,
                };
        componentDidMount(){
          let myData = yourStore.getData();
          this.setState({viewData:myData})
        }
        updateView(){
         let myData = yourStore.getData();
          this.setState({viewData:myData})
        }
    
    
    render() 
       {
        return(
          <div>
             {
          this.state.viewData && this.state.viewData.map(function (obj, index) {
            return <childComponenet data={obj} key={index}/>
           })
            }       
          </div>
         <button onClick={this.updateView.bind(this)>Update</button>}
         )
    }
    

    ChildComponent:

    constructor() {
            super();
            this.state = {
                childData:this.props.data
                }
            };
    
    //componentDidMount(){
      //this.setState({childData:this.props.data}) }
    
    componentWillReceiveProps(newProps){
       this.setState({childData:newProps.data})//this method will not get called first time
    }
    
    render(){
       return(
       <span>{this.state.childData}</span>
       )
    }
    

    Constructor is initialised only once. So when first time child component is rendered, it will set the state variable. Now as you click on update state in parent component, state is updated and it will pass the updated state as props to child component. In this case componentWillReceiveProps method will get called and it update the child component state.

    Note: componentWillReceiveProps not checks the internal value of props. It means even though previous and current props is same, it will be in action. Hence the answer is YES. It will get called every time, when it receives new props from parent.

    0 讨论(0)
  • 2021-01-15 01:31

    As suggested by Brandon in comments:

    yes. It will get called everytime the component will receive possibly new props. It does not get called on the initial render

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