Will componentWillRecieveProps run every time props are received

后端 未结 2 697
遇见更好的自我
遇见更好的自我 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(
          
    { this.state.viewData && this.state.viewData.map(function (obj, index) { return }) }
    } ) }

    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(
       {this.state.childData}
       )
    }
    

    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.

提交回复
热议问题