I know how to do it with functional components (unless I'm mistaken).
const [childComponentStateVar, setChildComponentStateVar] = useState()
useEffect(() => {
setChildComponentStateVar(context.newDataFromParent)
}, [context.newDataFromParent])
In this example every time context.newDataFromParent changes, the state will get updated.
But I don't know the equivalent in class based components and I haven't been able to find it online. Any help?
My other question is, does it ever make sense to do this?
componentWillReceiveProps
lifecycle function of the component.class Component extends React.Components {
componentWillReceiveProps = (nextProps) => {
if (nextProps.data !== this.props.data) {
this.props.setChildComponentStateVar(data)
}
}
render() {
return ( <div /> );
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.