【问题标题】:Dynamically populate Select options via API call in React Final Form在 React Final Form 中通过 API 调用动态填充 Select 选项
【发布时间】:2020-05-15 16:25:04
【问题描述】:

我正在使用react-final-formreact-final-form-listeners。我表单中的第一个字段是员工搜索。当用户选择员工时,我需要调用 API 来检索与该员工关联的所有文档,然后使用获取的文档名称填充 Select

<Form
  render={({
    handleSubmit, form, submitting, pristine,
  }) => (
    <form onSubmit={handleSubmit}>
    <Paper>
        <div>
        <InputLabel>Employee</InputLabel>
        <Field
            name="employee"
            label="Employee"
            component={employeeSearchAdapter}
        />
        <OnChange name="employee">
          {(employee) => {
            if (employee.employeeId) {
              fetchDocs(`/docs?empPin=${employee.employeeId}`, 'get')
                .then(res => res.json())
                .then(data => setDocs(data))
                .catch((err) => {
                  console.log(err);
                });
            }
          }}
        </OnChange>
        </div>
        <div>
        <Field
            label="Documents"
            name="documents"
            component={Select}
        >
            {docs ? docs.map(doc => <MenuItem key={doc.docId} value={doc.docName}>{doc.docName}</MenuItem>) : <MenuItem key="default" value="default">Select an Employee</MenuItem>}
        </Field>
        </div>
    </Paper>
    </form>
    )}
  />

问题是调用setDocs(data) 会重新呈现整个表单,并且所有其他字段都被清除了它们的选定值。我尝试以类似的方式使用&lt;FormSpy /&gt;,但遇到了同样的问题。如何在不丢失用户已经输入的值的情况下加载这些数据?

【问题讨论】:

  • 我有同样的问题你找到解决办法了吗?

标签: javascript reactjs react-final-form


【解决方案1】:

如果可以考虑改用react-final-form-hooks 那么你就可以使用useEffect钩子了。

import { useForm } from "react-final-form-hooks";
...
const [ options, setOptions ] = useState([]);
const { form, handleSubmit, submitting } = useForm({
    onSubmit,
    mutators,
    initialValues,
    ...
});
useEffect(() => {
   // fetch and setOptions
}, [form.getState().values.column]);

...
return (
    <form onSubmit={handleSubmit}>
        ...
    </form>
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 2015-12-17
    • 2020-08-10
    相关资源
    最近更新 更多