![](/img/trans.png)
[英]How to update a parent's component state from a child component in Reactjs
[英]How to update state in child component with context value from parent (class components)
我知道如何使用功能組件來做到這一點(除非我弄錯了)。
const [childComponentStateVar, setChildComponentStateVar] = useState()
useEffect(() => {
setChildComponentStateVar(context.newDataFromParent)
}, [context.newDataFromParent])
在此示例中,每次 context.newDataFromParent 更改時,state 都會更新。
但我不知道基於 class 的組件中的等價物,而且我無法在網上找到它。 有什么幫助嗎?
我的另一個問題是,這樣做有意義嗎?
componentWillReceiveProps
生命周期 function 來完成。class Component extends React.Components {
componentWillReceiveProps = (nextProps) => {
if (nextProps.data !== this.props.data) {
this.props.setChildComponentStateVar(data)
}
}
render() {
return ( <div /> );
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.