Updating state on props change in React Form

前端 未结 11 1973
时光说笑
时光说笑 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:20

    Apparently things are changing.... getDerivedStateFromProps() is now the preferred function.

    class Component extends React.Component {
      static getDerivedStateFromProps(props, current_state) {
        if (current_state.value !== props.value) {
          return {
            value: props.value,
            computed_prop: heavy_computation(props.value)
          }
        }
        return null
      }
    }

    (above code by danburzo @ github )

提交回复
热议问题