English 中文(简体)
原始表格在初始时不提供 价值的变化
原标题:antd form is not rendered when initialValues changed

我正在从使用中获取数据,供我初步使用。 当我检查我的构成部分时,一切都是 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?

问题回答

At the bottom of Form.Item section, the documentation mentions:

请注意,<条码>初始数值不能通过<条码>更新,<> > > > 日<国>/条码>在此种情况下可动态使用<条码>。

此外,你忘记了<代码>form的监控例: to the <Form /> part。 然后,你可以打电话instance methods





相关问题
C# Form Problem: new form losing control and randomly hiding

I m encountering strange behavior with forms on a c# 3.5 app. On a button click, my form1 hides itself, creates a new form2, and shows form2. Form1 also contains the event method triggered when ...

TCPlistener.BeginAcceptSocket - async question

Some time ago I have payed to a programmer for doing multithread server. In the meantime I have learned C# a bit and now I think I can see the slowndown problem - I was told by that guy that nothing ...

RoR: before_save on nested object in form?

I have a form with a nested object (customer < order), and it works except that it keeps creating a new customer record. I d like to have it check to see if an existing customer is already ...

Receive POST from External Form

I have a form on another website (using a different backend) that I want to be able to POST to my Rails application (on a different domain). How do I generate a valid authenticity token for the ...

Getting posted values in MVC PartialView

I ve created a PartialView which I render with Html.RenderPartial, passing the name of the view and the strongly-typed data item to bind to (below): <% Html.RenderPartial("...

Recaptcha - Form Customization

Does anyone know if recaptcha can be fully customize without the default frame. I need the recaptcha image to only be a certain width as well as the input field. Has anyone done this before with ...

Better way to retain form data on manual back redirect?

I have a form that, on submit, requires the customer to look over the data, and then confirm the changes before saving the data. However, I m using a really rough way of retaining data if the user ...

热门标签