我正在从使用中获取数据,供我初步使用。 当我检查我的构成部分时,一切都是 o。 但是,当用户更新一页时,我的价值观就被ui灭了。 但是,我可以看到在奥塞罗尔更新的初步估价。 我的相关守则部分是:
import {
Form,
} from "antd";
import { User } from "@/types/User";
import { useSession } from "next-auth/react";
const ProfileTab = () => {
const { data: session, update } = useSession();
const user = session?.user as User;
const initialValues = {
name: user?.name,
locale: user?.locale,
avatar: user?.avatar,
};
// At first, I tried to this useEffect to render Form component. But it didn t work. I saw updated values in the console but the form didn t render with the updated values.
// useEffect(() => {
// form.setFieldsValue({
// name: user?.name,
// locale: user?.locale,
// });
// }, [session, form]);
const onFinish = (values: FieldType) => {
let putValues: PutValues = {
name: values.name,
locale: values.locale,
};
api.client
.put("user", putValues)
.then((res) => {
notification.success({
message: "Profile updated",
});
if (user) {
// This function updates the session
update({
...session,
user: {
...user,
name: res.data.data.name,
avatar: res.data.data.avatar,
locale: res.data.data.locale,
},
});
}
})
.catch((res) => {...});
};
const onFinishFailed = () => {...};
const customizeRequiredMark = () => {...}
const onAvatarChange = () => {...}
return (
<div className="p-8">
{contextHolder}
<Form
key={JSON.stringify(initialValues)} // This is required to render the form again when the initialValues change
initialValues={initialValues}
labelCol={{ span: 4 }}
wrapperCol={{ span: 8 }}
colon={false}
layout="horizontal"
requiredMark={customizeRequiredMark}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
>
<Form.Item<FieldType>
name="name"
label={<Label label="Name" required />}
labelAlign="left"
rules={[{ required: true, message: "Name field is required" }]}
>
<Input size="large" />
</Form.Item>
<Form.Item<FieldType>
name="locale"
label={<Label label="Locale" />}
labelAlign="left"
>
<Select
size="large"
options={[
{ value: "ar", label: "Arabic" },
{ value: "en", label: "English" },
{ value: "tr", label: "Türkçe" },
]}
/>
</Form.Item>
<Form.Item wrapperCol={{ offset: 4, span: 8 }}>
<Button
loading={saving}
type="primary"
htmlType="submit"
size="large"
onClick={() => setSaving(true)}
>
Save
</Button>
</Form.Item>
</Form>
</div>
);
};
export default ProfileTab;
At first, I read and tried this suggestions. stackoverflow.com/61422607 but useEffect() hook was not solve my problem. Then I tried to use key
prop my component. It solve my problem but I am not sure it is best practise.
Could anyone provide insights or alternative solutions to ensure that my form retains the correct initial values even after a page refresh?