如何使用父组件(class 个组件)的上下文值更新子组件中的状态
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 更改时,状态都会更新。
但我不知道基于 class 的组件中的等价物,而且我无法在网上找到它。有帮助吗?
我的另一个问题是,这样做是否有意义?
- 在class个组件中,可以通过组件的
componentWillReceiveProps
生命周期函数来实现。
class Component extends React.Components {
componentWillReceiveProps = (nextProps) => {
if (nextProps.data !== this.props.data) {
this.props.setChildComponentStateVar(data)
}
}
render() {
return ( <div /> );
}
}
- 在没有任何用例背景的情况下很难回答问题
我知道如何使用功能组件来实现(除非我弄错了)。
const [childComponentStateVar, setChildComponentStateVar] = useState()
useEffect(() => {
setChildComponentStateVar(context.newDataFromParent)
}, [context.newDataFromParent])
在此示例中,每次 context.newDataFromParent 更改时,状态都会更新。
但我不知道基于 class 的组件中的等价物,而且我无法在网上找到它。有帮助吗?
我的另一个问题是,这样做是否有意义?
- 在class个组件中,可以通过组件的
componentWillReceiveProps
生命周期函数来实现。
class Component extends React.Components {
componentWillReceiveProps = (nextProps) => {
if (nextProps.data !== this.props.data) {
this.props.setChildComponentStateVar(data)
}
}
render() {
return ( <div /> );
}
}
- 在没有任何用例背景的情况下很难回答问题