Can't use state value as props for child component

前端 未结 1 1353
有刺的猬
有刺的猬 2021-01-25 10:23

In my react js app, I can\'t seem to use the state value as props for the child component.

In the parent component, constructor, the app has a null state ca

相关标签:
1条回答
  • 2021-01-25 10:44

    Possible solutions are:

    1. You are storing the props value in state of child component so, Update the state of child component whenever any change happen to props values (state of parent). For that use componentWillReceiveProps lifecycle method.

    componentWillReceiveProps():

    is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.

    Like this:

    componentWillReceiveProps(newProps){
       this.setState({
          value: newProps.productsByWarehouse
       });
    }
    

    Note: Replace value by the actual key in which you are storing the value.

    2. Don't store the props values in state of child component, directly use this.props.productsByWarehouse, Whenever you change the parent state values, child will automatically get the updated value in props.

    0 讨论(0)
提交回复
热议问题