【发布时间】: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 调用
标签: javascript arrays reactjs object