如何使用 API 响应作为 ReactJS 中输入的初始值

How to use an API response as initial value for input in ReactJS

你好我正在尝试创建一个输入字段,该字段已经具有来自 ReactJS 中 API 响应的预设值。我试过使用 console.log(data[0].name),它显示了我期望的值,当我尝试在前端显示它时,它也能正常工作。但是当我试图将它显示为我的输入字段的初始值时,它只会给我一个空的输入字段。 initialValue = {data[0].name}

这是我的 app.js

import React, { useEffect, useState } from "react";
import { Form, Button, Input } from "antd";

function App() {
  const [data, setData] = useState([{}]);
  const [form] = Form.useForm();
  const onFinish = (values) => {
    console.log("Received values of form: ", values);
  };

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts/1/comments")
      .then((res) => res.json())
      .then((data) => {
        setData(data);
        console.log(data);
      });
  }, []);

  return (
    <div>
      {" "}
      <Form form={form} onFinish={onFinish}>
        <Form.Item
          className="Form-label"
          name="firstName"
          label="First Name"
          initialValue={data[0].name}
        >
          <Input
            maxLength={10}
            style={{ minWidth: 200, maxWidth: 500 }}
            placeholder="Enter First Name"
          />
        </Form.Item>
        <Form.Item
          className="Form-label"
          name="middleName"
          label="Middle Name"
          initialValue=""
        >
          <Input
            maxLength={10}
            style={{ minWidth: 200, maxWidth: 500 }}
            placeholder="Enter Middle Name"
          />
        </Form.Item>
        <Form.Item>
          <div className="Btn-Primary-Create-Employee">
            <Button type="primary" htmlType="submit">
              Save
            </Button>
          </div>
        </Form.Item>
      </Form>
    </div>
  );
}

export default App;

这是我正在获取的对象

[
  {
    "postId": 1,
    "id": 1,
    "name": "id labore ex et quam laborum",
    "email": "Eliseo@gardner.biz",
    "body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
  },
  {
    "postId": 1,
    "id": 2,
    "name": "quo vero reiciendis velit similique earum",
    "email": "Jayne_Kuhic@sydney.com",
    "body": "est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et"
  }
]

我还制作了一个 codesandbox project 以更好地可视化我的问题

设置加载状态,不要return除非加载完成并且应该修复它。

import React, { useEffect, useState } from "react";
import { Form, Button, Input } from "antd";

function App() {
  const [data, setData] = useState([{}]);
  const [loading, setLoading] = useState(true);
  const [form] = Form.useForm();
  const onFinish = (values) => {
    console.log("Received values of form: ", values);
  };

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts/1/comments")
      .then((res) => res.json())
      .then((data) => {
        setData(data);
        setLoading(false);
        console.log(data);
      })
      .catch((err) => {
        setLoading(false);
      });
  }, []);

  if (!loading) {
    return (
      <div>
        {" "}
        <Form form={form} onFinish={onFinish}>
          <Form.Item
            className="Form-label"
            name="firstName"
            initialValue={data.length ? data[0].name : "email"}
            label="First Name"
          >
            <Input
              maxLength={10}
              style={{ minWidth: 200, maxWidth: 500 }}
              placeholder="Enter First Name"
            />
          </Form.Item>
          <Form.Item
            className="Form-label"
            initialValue={data.length ? data[0].name : "email"}
            name="email"
            label="email"
          >
            <Input
              maxLength={10}
              style={{ minWidth: 200, maxWidth: 500 }}
              placeholder="Enter Middle Name"
            />
          </Form.Item>
          <Form.Item>
            <div className="Btn-Primary-Create-Employee">
              <Button type="primary" htmlType="submit">
                Save
              </Button>
            </div>
          </Form.Item>
        </Form>
      </div>
    );
  }
  return null;
}

export default App;