将表单数据推送到对象数组

Posted

技术标签:

【中文标题】将表单数据推送到对象数组【英文标题】:Pushing form data to an array of objects 【发布时间】:2022-01-23 03:27:29 【问题描述】:

我有一个带有一个输入元素的表单。提交表单后,我希望将其推送到消息数组中。此代码只执行一次。第二次提交表单时,它只更改最后一条消息的值,而不是在其后添加新值。

import "./App.css";
import React,  useState, useEffect  from "react";

function App() 
  const chat = 
    messages: [
      
        to: "John",
        message: "Please send me the latest documents ASAP",
        from: "Ludwig",
      ,
    ],
  ;
  const [form, setForm] = useState("");

  function handleSubmit(e) 
    e.preventDefault();
    chat.messages.push(
      message: `$form`,
    );
    //this console.log below shows that the message from the form has been pushed successfully
    //however when the form is submitted again with a new value it just alters the above successfully pushed value
    //INSTEAD of adding a NEW value after it. The length of the array is INCREASED only once and that is the problem
    console.log(chat.messages);

    setForm("");
  

  return (
    <div>
      <form onSubmit=handleSubmit>
        <input
          type="text"
          value=form
          onChange=(e) => setForm(e.target.value)
        />
      </form>
    </div>
  );


export default App;

【问题讨论】:

chat 在每次渲染后重新创建。您可以在此处useRef 在渲染周期内保持值。 状态变量也会在渲染周期中保持不变,但它们会导致重新渲染。顺便说一句,我在您的代码中看不到任何 API 调用 【参考方案1】:

chat 必须是 state 变量。所以你可以使用类似下面的东西:

import React,  useState, useEffect  from "react";

function App() 
  const [chat, setChat] = useState(
    messages: [
      
        to: "John",
        message: "Please send me the latest documents ASAP",
        from: "Ludwig"
      
    ]
  );
  const [form, setForm] = useState("");

  function handleSubmit(e) 
    e.preventDefault();
    setChat((prev) => (
      messages: [
        ...prev.messages,
        
          message: `$form`
        
      ]
    ));
    //this console.log below shows that the message from the form has been pushed successfully
    //however when the form is submitted again with a new value it just alters the above successfully pushed value
    //INSTEAD of adding a NEW value after it. The length of the array is INCREASED only once and that is the problem
    console.log(chat.messages);

    setForm("");
  

  return (
    <div>
      <form onSubmit=handleSubmit>
        <input
          type="text"
          value=form
          onChange=(e) => setForm(e.target.value)
        />
      </form>
    </div>
  );


export default App;

【讨论】:

以上是关于将表单数据推送到对象数组的主要内容,如果未能解决你的问题,请参考以下文章

如何正确地将具有多个元素的新对象推送到数组中?

从异步回调函数将对象推送到本地数组

猫鼬:更新字段,将对象推送到数组中[重复]

使用 Mongoose 将项目推送到对象中的数组

如何避免在对象内部创建对象并使用猫鼬将元素直接推送到快速数组中?

如何承诺等待所有对象完成然后推送到数组?