Updating state on props change in React Form

前端 未结 11 1966
时光说笑
时光说笑 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 04:55

    The new hooks way of doing this is to use useEffect instead of componentWillReceiveProps the old way:

    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 });
      }
    }
    

    becomes the following in a functional hooks driven component:

    // store the startTime prop in local state
    const [startTime, setStartTime] = useState(props.startTime)
    // 
    useEffect(() => {
      if (props.startTime !== startTime) {
        setStartTime(props.startTime);
      }
    }, [props.startTime]);
    

    we set the state using setState, using useEffect we check for changes to the specified prop, and take the action to update the state on change of the prop.

提交回复
热议问题