gpt4 book ai didi

javascript - child Prop 如何更新?

转载 作者:行者123 更新时间:2023-11-30 10:59:14 24 4
gpt4 key购买 nike

我是 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”,这是意料之中的,但如果我挖掘一点,控制台显示:

old name is Tom

new name is Jerry

我的问题是,在我点击按钮之后,在Child 组件中,this.props.name 仍然是Tom,这意味着this.props 不是最新的 Prop ,而在 render() 函数中, this.props.name 变成了 Jerry,表示this.props是最新的prop。

旧 Prop 什么时候变成最新 Prop 的?在 shouldComponentUpdate() 之后是否有另一个生命周期方法实际上将 this.props 更改为最新的 Prop ,例如:

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

这样的生命周期方法存在吗?我知道名称不匹配,但是是否有生命周期方法可以完成上述功能?

最佳答案

不,没有这样的lifecycle method .

this 的 props 分配发生在库本身的生命周期方法之间(shouldComponentUpdate 之后,render 之前)并且没有 < em>public 接口(interface)如何干扰该过程。

关于javascript - child Prop 如何更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58592469/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com