[英]how children's props get updated?
我是 React 的新手,仍在努力学习如何更新 props 以及更新发生在哪些生命周期方法中。 下面是我写的一些代码:
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>
}
}
当我单击按钮时,段落的内容从“Tom”变为“Jerry”,这是意料之中的,但如果我稍微挖掘一下,控制台会显示:
旧名是汤姆
新名字是杰瑞
我的问题是,点击按钮后,在Child
组件中, this.props.name
仍然是Tom
,这意味着this.props
不是最新的道具,而在render()
function 中, this.props.name
变成了Jerry
,这意味着this.props
是最新的道具。
什么时候旧的道具变成了最新的道具? 在shouldComponentUpdate()
之后是否有另一个生命周期方法实际上将this.props
更改为最新的道具,例如:
afterShouldComponentUpdate(newProps, newState){
...
this.props = newProps;
}
这样的生命周期方法是否存在? 我知道名称不匹配,但是否有实现上述功能的生命周期方法?
不,没有这样的生命周期方法。
this
道具的分配是由库本身在生命周期方法之间(在shouldComponentUpdate
之后,在render
之前)进行的,并且没有公共接口如何干扰该过程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.