在表单中创建新的 json 元素时,我不明白 id 来自哪里(React Hooks)

发布于 2025-01-10 02:28:09 字数 3537 浏览 2 评论 0原文

我有一个带有 React Hooks 的 CRUD 表单,可以正常工作,问题是我没有表明该项目是使用唯一 ID 创建的,但它却拥有它。拥有一个独特的ID是我感兴趣的事情,但我不明白它从何而来。代码的任何部分是否会导致它被创建?我很困惑。

我正在使用 JSON 服务器。

这是 json:

{
  "posts": [
    {
      "id": 15,
      "title": "ho",
      "author": "Autor de ejemplo",
      "content": "Contenido."
    }
  ]
}

这是使用 POST 方法获取:

export function setPost(posts: IPost) {
  return fetch('http://localhost:3004/posts', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(posts)
  })
    .then(response => response.json())
}

这是形式:

interface ErrorMessageProps {
    message: string;
}

const ErrorMessage: React.FC<ErrorMessageProps> = props => {
    return (
        <div className="errorEmpty">
            {props.message}
        </div>
    );
};

const New: React.FC = () => {
    const [newPost, setNewPost] = useState({
        id: Number(''),
        title: '',
        author: '',
        content: ''
    })
    const [error, setError] = useState('')

    let navigate = useNavigate();

    const handleInputChange = (e: React.FormEvent<HTMLInputElement>) => {
        console.log((e.target as HTMLInputElement).value)
        setNewPost({
            ...newPost,
            [(e.target as HTMLInputElement).name]: (e.target as HTMLInputElement).value
        })
    };

    const createPost = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        if (!newPost.title || !newPost.author || !newPost.content) {
            setError("¡No dejes campos vacíos!")
        } else {
            setPost(newPost);
            navigate("/");
        }
    }

    return (
        <div className="containerHomepage">
            <form className="formulari" onSubmit={createPost}>
                <div className="containerBreadCrumb">
                    <ul className="breadCrumb">
                        <li>Posts</li>
                    </ul>
                </div>

                <div className="containerTitleButton">
                    <input
                        className=""
                        type="text"
                        placeholder='Post title'
                        name="title"
                        onChange={handleInputChange}
                    ></input>
                    <button
                        className="button"
                        type="submit"
                    >Save</button>
                </div>

                <div className="containerEdit">
                    <input
                        className="editAuthor"
                        type="text"
                        placeholder='Author'
                        name="author"
                        onChange={handleInputChange}
                    ></input>
                    <input
                        className="editContent"
                        type="textarea"
                        placeholder='Content'
                        name="content"
                        onChange={handleInputChange}
                    ></input>
                    < ErrorMessage
                        message={error}
                    />
                </div>

            </form>
        </div>
    );
};


// ========================================

export default New;

I have a CRUD form with React Hooks that works correctly, the problem is that I have not indicated that the item is created with a unique ID and yet it has it. Having a unique ID is something that interests me, but I don't understand where it comes from. Does any part of the code cause it to be created? I'm very confused.

Im using JSON Server.

This is the json:

{
  "posts": [
    {
      "id": 15,
      "title": "ho",
      "author": "Autor de ejemplo",
      "content": "Contenido."
    }
  ]
}

This is the fetch with the POST method:

export function setPost(posts: IPost) {
  return fetch('http://localhost:3004/posts', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(posts)
  })
    .then(response => response.json())
}

And this is the form:

interface ErrorMessageProps {
    message: string;
}

const ErrorMessage: React.FC<ErrorMessageProps> = props => {
    return (
        <div className="errorEmpty">
            {props.message}
        </div>
    );
};

const New: React.FC = () => {
    const [newPost, setNewPost] = useState({
        id: Number(''),
        title: '',
        author: '',
        content: ''
    })
    const [error, setError] = useState('')

    let navigate = useNavigate();

    const handleInputChange = (e: React.FormEvent<HTMLInputElement>) => {
        console.log((e.target as HTMLInputElement).value)
        setNewPost({
            ...newPost,
            [(e.target as HTMLInputElement).name]: (e.target as HTMLInputElement).value
        })
    };

    const createPost = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        if (!newPost.title || !newPost.author || !newPost.content) {
            setError("¡No dejes campos vacíos!")
        } else {
            setPost(newPost);
            navigate("/");
        }
    }

    return (
        <div className="containerHomepage">
            <form className="formulari" onSubmit={createPost}>
                <div className="containerBreadCrumb">
                    <ul className="breadCrumb">
                        <li>Posts</li>
                    </ul>
                </div>

                <div className="containerTitleButton">
                    <input
                        className=""
                        type="text"
                        placeholder='Post title'
                        name="title"
                        onChange={handleInputChange}
                    ></input>
                    <button
                        className="button"
                        type="submit"
                    >Save</button>
                </div>

                <div className="containerEdit">
                    <input
                        className="editAuthor"
                        type="text"
                        placeholder='Author'
                        name="author"
                        onChange={handleInputChange}
                    ></input>
                    <input
                        className="editContent"
                        type="textarea"
                        placeholder='Content'
                        name="content"
                        onChange={handleInputChange}
                    ></input>
                    < ErrorMessage
                        message={error}
                    />
                </div>

            </form>
        </div>
    );
};


// ========================================

export default New;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文