【问题标题】:Formik - setting dynamic values for select boxFormik - 为选择框设置动态值
【发布时间】:2020-11-08 08:03:43
【问题描述】:

当用户选择国家时,我有一个包含国家和州字段的地址表单,我想在后端获取州列表表单并更新州选择框值列表。

我参考了下面的文章来创建表单。 https://medium.com/@nphivu414/build-a-multi-step-form-with-react-hooks-formik-yup-and-materialui-fa4f73545598enter image description here

【问题讨论】:

  • 你是说预选状态吧?

标签: reactjs formik yup formik-material-ui


【解决方案1】:

首先你可以像下面这样设置初始值

const initialValues = {
    otherValues: '',
    address: {
        line_1: '',
        zip_code: '',
        city: '',
        state: '',
    },
};

然后根据这个初始值,你可以启动如下状态:

const [initialAddress, updateInitialAddress] = useState(initialValues);

之后,在 UseEffect 中调用 API 获取地址,您可以像下面这样更新状态:

 //say your response set in "res" variable

 updateInitialAddress({
    otherValues: res.other_values,
    address: {
      line_1: res.line_1,
      zip_code: res.zip_code,
      city: res.city,
      state: res.state,
      },
  });

然后你可以在formik中设置:

initialValues={initialAddress}

如果您的 Formik Select Dropdown 与您初始化的名称相同,那么它将在下拉列表中自动选择。

谢谢

【讨论】:

  • 谢谢,但是如何使用 formik 在处理程序中侦听字段值更改并访问它 - 在更改国家/地区字段调用处理程序时读取国家/地区值并将其传递给后端请求以获取状态列表
  • 如果您使用 Formik,因此您将在“值”中获得更新的更改值,请阅读 formik 文档如何获取更改值的值
猜你喜欢
  • 1970-01-01
  • 2021-04-04
  • 1970-01-01
  • 1970-01-01
  • 2020-08-17
  • 2017-11-13
  • 2018-02-28
  • 2016-03-19
  • 1970-01-01
相关资源
最近更新 更多