React: state 数组增加新元素

组件的 state 不允许直接修改,只能读。
如果 state 为数组,需要向数组push新元素,不能使用push()操作。

1. 方法1. 使用concat()操作。

push() 增加新元素到数组末尾,返回数组新的长度,因此修改原始数组。

concat() 合并数组,不修改已有的数组,而是返回合并后的新数组,例如:

return state.concat(newItem);

方法2. 使用ES6 展开操作符

使用展开操作符 … 返回新数组, 不会修改原始数组:

return [...state, newItem];

spread/rest operator 举例:

可以作用于数组:

let arr1 = [2, 3];
let arr2 = [1, ...arr1, 4];
console.log(arr2);
// [1, 2, 3, 4]

let s = 'split';
console.log(...s);
// s p l i t

也可以作用于对象:

let obj1 = { 1: 'one' };
let obj2 = { 2: 'two' };
let obj3 = { ...obj1, ...obj2 };
console.log(obj3);
// { 1: 'one', 2: 'two' }

Rest parameter syntax looks the same as spread syntax but actually represents an unknown number of function arguments as an array. So rather than “unpacking” the iterable, rest parameters actually package multiple arguments into an array.

const multiArgs = (...args) => {
   console.log(args);
}

multiArgs('a', 'b', 'c');
// ['a', 'b', 'c']

https://stackoverflow.com/questions/34559918/spread-syntax-es6/57680090


版权声明:本文为ftell原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。