我遇到了这种奇怪的行为,我不知道如何解决,在此表单的编辑模式下,如果刷新页面,我会遇到一个错误,其中值和占位符都显示在字段中
-- 这是我的表单组件
const Form = () => {
// fetch hook to get the settings data.
const settings = useGetSettingsQuery();
// initialize the useFormik hook with the data just fetched
const form = useSettingsForm({ initialValues: settings.data?.data ?? {} });
return (
<Box>
<Grid container spacing={2}>
<Grid item xs={12}>
<TextField
fullWidth
name={'id'}
label={'id'}
placeholder={'ticket id'}
variant="outlined"
value={form.values.id}
onChange={form.handleChange}
/>
</Grid>
<Grid item xs={12}>
initial values
<pre>{JSON.stringify({ id: form.initialValues.id }, null, 2)}</pre>
</Grid>
<Grid item xs={12}>
current value values
<pre>{JSON.stringify({ id: form.values.id }, null, 2)}</pre>
</Grid>
</Grid>
</Box>
);
};
-- 这是我的钩子,现在我已经删除了钩子中的所有内容,这就是剩下的:
export const useSettingsForm = ({ initialValues }: Props) => {
return useFormik<Partial<ISetting>>({
enableReinitialize: true,
initialValues: {
...initialValues,
},
validationSchema: Yup.object().shape({}),
onSubmit: async (values) => {
console.log('submitted -> ', values);
},
});
};
目前的行为
对于我的
useGetSettings
钩子,我使用 RTK 查询来获取数据并处理服务器状态,这是 apiSlice
的片段:
export const settingApiSlice = apiSlice.injectEndpoints({
endpoints(builder) {
return {
getSettings: builder.query<IGetSettingsResp, void>({
query() {
return `/setting`;
},
providesTags: ['setting'],
}),
};
},
});
export const { useGetSettingsQuery } = settingApiSlice;
如图所示,显示了占位符文本和值,有什么方法可以修复此错误,谢谢
在
Formik
中,输入的 name
与 property
内的值的 form.values
相关联。所以这个:
<TextField
fullWidth
name={'ticket number'}
label={'ticket number'}
placeholder={'ticket number'}
variant="outlined"
value={form.values.id}
onChange={form.handleChange}
/>
应该是这样的:
<TextField
fullWidth
name="id"
label={'ticket number'}
placeholder={'ticket number'}
variant="outlined"
value={form.values.id}
onChange={form.handleChange}
/>
当您使用
name={'ticket number'}
(或 name="ticket number"
)时,它实际上是在尝试在 form.values.ticket number
而不是 form.values.id
上设置值,正如您所希望的那样,因为那是您的 value
。
id
中的value={form.values.id}
连接到name="id"
。