{..action.response}react.js或redux中的这3个点有什么用



react.js或redux 中的这3个点有什么用

const something = (state = initState, action) => {
switch (action.type) {
case something:
return { ...action.response };
default:
return state;
}
};

这是一个ES6功能,扩展箭头运算符。排列语法允许要在多个参数或需要多个元素。

let a = [1,2,3,4];
let b = [...a, 5,6,7];
console.log(b); //1,2,3,4,5,6,7

它被称为spread语法,用于创建对象或数组的浅层副本[…array]。React中的主要用途之一是创建副本,以便在更新状态时不会更改原始数据:

[state, setState] = useState(...);
const tempState = {...state};
tempState.key = newValue;
setState(tempState);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

但请注意,浅复制意味着只有顶部的键和值才真正创建新的嵌套键和值,并引用到原始对象。这可能会产生错误,因此对于嵌套的对象和数组,最好使用库进行深度克隆,例如Lodash的cloneDeep。

https://alligator.io/js/deep-cloning-javascript-objects/

最新更新