我正在将我的父状态传递给我的子组件,但是当我在子组件中打印道具时,我获得了父组件的先前状态而不是最新状态。我很确定这是因为this.setState是异步的。
handleClick(event) {
const value = event.currentTarget.value;
this.setState({ touched: value });
}
render() {
return(
<ChildComponent {...this.state} />
)
}
Run Code Online (Sandbox Code Playgroud)
componentWillReceiveProps在组件更新渲染之前。如果您阅读文档,他们会解释您对下一个道具的引用。
componentWillReceiveProps(nextProps, nextState){
this.props.something // old value
nextProps.something // new value
}
Run Code Online (Sandbox Code Playgroud)
现在在渲染完成后会发生更新。
componentDidUpdate(previousProps){
this.props.somehting // new value
previousProps.something // old value
}
Run Code Online (Sandbox Code Playgroud)
您的问题是您在新道具更改以更新旧道具之前打印了旧道具。你需要的是componentDidUpdate或者看看下一个进来的道具
| 归档时间: |
|
| 查看次数: |
2641 次 |
| 最近记录: |