如何将状态值传递给form j中的formik中的初始值

问题描述 投票:1回答:2

我在我的反应应用程序中使用了formik库。最初,我在构造函数中声明了状态值,在componentDidMount中我正在使用该应用响应调用API更新状态值,任何人都可以帮助我将状态值传递给fomik初始值

在我的情况下,formik采用在构造函数中提前声明的初始状态值

class Dropdown extends Component {

        constructor(props) {
            super(props);
            this.state = {
              //some data
            };
          }
          componentDidMount() {
           //api call
           this.setState( {
              //update state values with api response data
            });  
         }
       render() {
            return (
            <Formik
              initialValues={this.state}
              validate={validate(validationSchema)}
              onSubmit={onSubmit}
              render={
                ({
                  values,
                  errors,
                  touched,
                  status,
                  dirty,
                  handleChange,
                  handleBlur,
                  handleSubmit,
                  isSubmitting,
                  isValid,
                  handleReset,
                  setTouched
                }) => ( 
                 //form uses initialValues
              )} />
              )
            }
    }
reactjs jsx formik
2个回答
2
投票

添加enableReinitialize到formik解决了我的问题

     <Formik
          enableReinitialize
          ..
          render={
            ({
              ..
            }) => ( 
             //form uses initialValues
          )} />

1
投票

您可以在initialValues prop处强制设置每个值:

 <Formik
  initialValues={
    formValue1: this.state.value1,
    formValue2: this.state.value2,
    ...
  }
  validate={validate(validationSchema)}
  onSubmit={onSubmit}
  render={
    ({
      values,
      errors,
      touched,
      status,
      dirty,
      handleChange,
      handleBlur,
      handleSubmit,
      isSubmitting,
      isValid,
      handleReset,
      setTouched
    }) => ( 
         //form uses initialValues
    )
  } 
/>
© www.soinside.com 2019 - 2024. All rights reserved.