繁体   English   中英

在反应挂钩中将元素添加到现有数组

[英]Adding an element to an existing array in react hooks

所以我有这个 state 变量:

const [Class, setClass] = useState({ Teacher: "John Fartsalot", Year: 2021, Students: [] });

我有一个:

ver studentObject

我想使用setClassstudentObject动态地推送到Students数组中。

我看到这篇文章: React Hooks 中的 Push 方法(useState)? 但它似乎只有在只有列表的情况下才有意义。

就我而言,正确的做法是什么?

这是添加的正确方法:

setStudents(students => [...students, studentObject]);

While you could spread the existing Class into a new object, and then spread the new students array into that new object as well, it would be better to follow the convention and separate out the state variables (as React recommends), and to not use Class作为变量名(它非常接近保留字class )。 考虑:

const [teacher, setTeacher] = useState('John Fartsalot');
const [year, setYear] = useState(2021);
const [students, setStudents] = useState([]);

然后添加到学生数组中,执行

setStudents([...students, studentObject]);

或者,如果students此时恰好处于陈旧的关闭状态,那么

setStudents(students => [...students, studentObject]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM