简体   繁体   English

儿童道具如何更新?

[英]how children's props get updated?

I'm new to React, still struggling to learn how props get updated and in which lifecycle methods the update takes place.我是 React 的新手,仍在努力学习如何更新 props 以及更新发生在哪些生命周期方法中。 Below is some code I wrote:下面是我写的一些代码:

export default Parent extends Component {
   constructor(props) {
    super(props);
    this.state = {
      name: "Tom"
    }
  }

  changeName = () => {
    this.setState({ name: "Jerry" });
  }
   
  render() {
    return <div>
             <Child name={this.state.name}/>
             <button onClick={this.changeName }>Change Name</button>
          </div>
  }
}
  
  
export default Child extends Component {
  ...
  shouldComponentUpdate(newProps, newState) {
     console.log("old name is" + this.props.name)
     console.log("new name is" + newProps.name)
     return true;
  }

  render() {
     return <p>{this.props.name}</p>
  }
}

When I click the button, the content of paragraph changes from "Tom" to "Jerry", which is expected, but if I dig a little bit, the console showed that:当我单击按钮时,段落的内容从“Tom”变为“Jerry”,这是意料之中的,但如果我稍微挖掘一下,控制台会显示:

old name is Tom旧名是汤姆

new name is Jerry新名字是杰瑞

My question is, after I click the button, inside the Child component, this.props.name is still Tom , which means this.props is not the latest props, while inside the render() function, this.props.name becomes Jerry , which means this.props is the latest prop.我的问题是,点击按钮后,在Child组件中, this.props.name仍然是Tom ,这意味着this.props不是最新的道具,而在render() function 中, this.props.name变成了Jerry ,这意味着this.props是最新的道具。

When did the old prop change to the latest prop?什么时候旧的道具变成了最新的道具? Is there another lifecycle method after shouldComponentUpdate() that actually changes this.props to the latest props, for example:shouldComponentUpdate()之后是否有另一个生命周期方法实际上将this.props更改为最新的道具,例如:

afterShouldComponentUpdate(newProps, newState){
   ...
   this.props = newProps;
}

Does such a lifecycle method exist?这样的生命周期方法是否存在? I know the name won't match, but is there a lifecycle method that accomplishes the above functionality?我知道名称不匹配,但是否有实现上述功能的生命周期方法?

No, there is no such lifecycle method .不,没有这样的生命周期方法

Assignment of props to this is happening BETWEEN lifecycle methods (after shouldComponentUpdate , before render ) by the library itself and there is no public interface how you can interfere with the process. this道具的分配是由库本身在生命周期方法之间(在shouldComponentUpdate之后,在render之前)进行的,并且没有公共接口如何干扰该过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM