gpt4 book ai didi

javascript - Formik + React Form 中的下拉列表和值未更新

转载 作者:行者123 更新时间:2023-12-05 04:00:42 25 4
gpt4 key购买 nike

以下是我的代码面临的问题-

  1. 商品下拉列表初始化不正确 - 我期望 commodity 2 在加载时可用,但它正在占用 commodity 1 RESOVLED initialValue={values.commodity.value} 应该在商品选择中。
  2. 从商品下拉列表更改商品时,植物下拉列表根本没有更新。 [仍在等待中]

工作示例 - https://codesandbox.io/s/ql95jvpxq4 (正确的行为)

我试图用我的 Select 复制相同的内容,但不知何故它不起作用。让我知道我在这里做错了什么。

错误代码 - https://codesandbox.io/s/01qno3vmvl

代码-

const formikEnhancer = withFormik({
mapPropsToValues: props => ({
commodity: { value: "commodity2", label: "commodity2" },
plant: { value: "Plant3", label: "Plant3" }
}),
handleSubmit: (values, { setSubmitting }) => {
const payload = {
...values,
commodity: values.commodity.value,
plant: values.plant.value
};
setTimeout(() => {
alert(JSON.stringify(payload, null, 2));
setSubmitting(false);
}, 1000);
},
displayName: "MyForm"
});

表格-

<form onSubmit={handleSubmit}>
<div style={{ margin: "1rem 0" }}>
<label htmlFor="commodity" style={{ display: "block" }}>
Commodity
</label>
<Select
id="commodity"
name="commodity"
value={commodities}
initialValue={values.commodity}
onChange={(field, value) => {
console.log(value);
setFieldValue("plant", plants[value][0]);
}}
/>
</div>
<div style={{ margin: "1rem 0" }}>
<label htmlFor="plant" style={{ display: "block" }}>
Plant
</label>
<Select
id="plant"
name="plant"
value={plants[values.commodity.value]}
onChange={setFieldValue}
/>
</div>

<button
type="button"
className="outline"
onClick={handleReset}
disabled={!dirty || isSubmitting}
>
Reset
</button>
<button type="submit" disabled={isSubmitting}>
Submit
</button>

<DisplayFormikState {...this.props} />
</form>

仅供引用 - 我是 formik 的新手,所以我可能遗漏了一些很常见的东西。

最佳答案

initialValue 设置错误。它应该是字符串值而不是对象。选择值正在使用父组件的状态和 Prop 进行更改。

这是工作变体 https://codesandbox.io/embed/n102qqq0nl

关于javascript - Formik + React Form 中的下拉列表和值未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55989921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com