简体   繁体   中英

How to update state in child component with context value from parent (class components)

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?

  1. In class components, you can do it with the 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 /> );
  }
}
  1. Hard to answer the question without any context of your use case

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM