<分区>
我是 ReactJS 世界的新手, 我想更新包含对象数组的 useState Hook ,但它现在正在根据我的要求更新数据 请帮助我。
ContactForm.js
function ContactForm() {
const [user, setUser] = useState([]);
const submitForm = () => {
console.log(user);
};
return (
<div>
<input
type="text"
placeholder="name"
onChange={(e) =>
setUser((state) => [...state, { user_name: e.target.value }])
}
value={user.user_name}
/>
<input
type="text"
placeholder="mobile"
onChange={(e) =>
setUser([...user, [...user, { mobile_number: e.target.value }]])
}
value={user.mobile_number}
/>
<button onClick={submitForm}>Submit</button>
</div>
);
}
我在期待类似的东西
[{
user_name:"abc",
mobile_number:"123"
}]
应该存储在我的状态中,但我得到了一些不同的输出,如下所示
0: {user_name: "a"}
1: {user_name: "as"}
2: {user_name: "asd"}
3: (4) [{…}, {…}, {…}, {…}]
4: (5) [{…}, {…}, {…}, Array(4), {…}]
5: (6) [{…}, {…}, {…}, Array(4), Array(5), {…}]
请帮我解决这个问题,请告诉我 useState 数组中的对象是如何工作的 提前致谢
(更新堆栈) 我尝试了很多方法,这就是为什么您可能会感觉到我用代码编写的内容,尤其是在
<input/>
标签