componentWillRecieveProps会运行吗

componentWillRecieveProps会运行吗

本文介绍了每当收到道具时,componentWillRecieveProps会运行吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读React facebook的文档,并且那里写道:

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

,但稍后在链接已被解释为,即使道具相同,也将调用此方法,因为道具可以作为引用,并且这些引用处的数据可能不同.

but later in this link, it has been explained that even if the props are same then this method is called because the props can be references and the data at those references might be different.

所以,我的问题是,每当我们收到新的道具时都调用它.

So, My question is whether it is called every time we receive new props.

推荐答案

初始呈现是指首次使用组件中的任何数据加载组件时.例如:

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>
   )
}

构造函数仅初始化一次.因此,当第一次呈现子组件时,它将设置 state 变量.现在,当您单击父组件中的更新状态时,会更新 state ,并将更新后的 state 作为 props 传递给子组件.在这种情况下,将调用 componentWillReceiveProps 方法并更新子组件状态.

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.

注意: componentWillReceiveProps 不检查道具的内部值.这意味着即使以前的道具和当前的道具相同,它也会起作用.因此,答案是.每当它从父母那里收到新道具时,就会被调用.

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.

这篇关于每当收到道具时,componentWillRecieveProps会运行吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 00:13