Updating state on props change in React Form

前端 未结 11 1961
时光说笑
时光说笑 2020-12-02 04:15

I am having trouble with a React form and managing the state properly. I have a time input field in a form (in a modal). The initial value is set as a state variable in

11条回答
  •  死守一世寂寞
    2020-12-02 05:11

    componentWillReceiveProps is depcricated since react 16: use getDerivedStateFromProps instead

    If I understand correctly, you have a parent component that is passing start_time down to the ModalBody component which assigns it to its own state? And you want to update that time from the parent, not a child component.

    React has some tips on dealing with this scenario. (Note, this is an old article that has since been removed from the web. Here's a link to the current doc on component props).

    Using props to generate state in getInitialState often leads to duplication of "source of truth", i.e. where the real data is. This is because getInitialState is only invoked when the component is first created.

    Whenever possible, compute values on-the-fly to ensure that they don't get out of sync later on and cause maintenance trouble.

    Basically, whenever you assign parent's props to a child's state the render method isn't always called on prop update. You have to invoke it manually, using the componentWillReceiveProps method.

    componentWillReceiveProps(nextProps) {
      // You don't have to do this check first, but it can help prevent an unneeded render
      if (nextProps.startTime !== this.state.startTime) {
        this.setState({ startTime: nextProps.startTime });
      }
    }
    

提交回复
热议问题