addPerson = (person) => {
this.setState(prevState => {
const people = [...prevState.people, person]
return {people}
})
}
有问题的行是 const people = [...prevState.people, person]
我意识到 ...prevState.people 正在将 people 数组的先前状态传播到(一个新数组??[]??)我对这里的逗号表示什么感到困惑。
最佳答案
您可以将 [...prevState.people, person]
视为一种奇特的书写方式 .push()
prevState.people.push(person) // returns the new length of the `people` array
但是,有一个关键的区别,这里,.push
修改了prevState.people
数组。而使用:
[...prevState.people, person] // "returns" this array
给出一个新数组,让prevState.people
保持不变。因此,您可以将新数组保存在变量中。在您的示例中,它保存在变量 people
中。
例如,如果你取数组:
const a = [1, 2, 3];
并将其传播到另一个数组中:
const b = [...a, 4];
然后此处的扩展运算符表示将 a
的内容转储/移动到 新数组 中,然后是 4
,这是另一个新数组中的元素。
因此 b
的输出将是:
[1, 2, 3, 4]
const a = [1, 2, 3];
const b = [...a, 4]; // create a new array, put the elements of 'a' into this new array. Add another element '4' to the end of this new array
console.log(b);
您可以阅读更多关于传播语法的信息 here
关于javascript - 这行代码在 react 方法中做什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54474089/