gpt4 book ai didi

javascript - 有人可以解释以下示例中 ...spread 运算符的使用吗?

转载 作者:行者123 更新时间:2023-12-02 23:36:16 26 4
gpt4 key购买 nike

根据我的理解,这就是展开运算符的工作原理:

x=[1,2,3];

y=[...x,4,5];

// this is same as y=[1,2,3,4,5]

const initialState={
ingredients: [
new Ingredient('Apples', 5),
new Ingredient('Tomatoes', 10),
]
};
export function shoppingListReducer( state=initialState, action:ShoppingListActions.ShoppingListActions ) {
switch(action.type) {
case ShoppingListActions.ADD_INGREDIENT:
return {
...state,
ingredients:[...state.ingredients,action.payload ]
}

default:
return state;
}

在上面的例子中,什么是

return {
...state,
ingredients:[...state.ingredients,action.payload ]
}

评价为?

有效负载的类型为成分:

export class Ingredient {
constructor(public name: string, public amount: number) {}
}

最佳答案

基本上,您正在尝试创建一个具有 state 对象的所有属性的对象,并使用 state.ingredients 中的所有值来覆盖其属性 ingredients 数组以及 action.payload。这样做可能是为了将结果对象的引用与状态对象分开。

var state = {
"someprop" : "somevalue",
"ingredients" : ["a", "b"]
};

var action = {
"payload" : 4
};

var result = {
...state,
ingredients:[...state.ingredients,action.payload ]
};
state.someprop = "somevalue1"; // does not alter result object
state.ingredients.push("c"); // does not alter result object
console.log(result);

或者,为了更好地理解它,您可以将其分解为以下内容

var result = {...state};
result.ingredients = [...state.ingredients, action.payload];

注意:如果 state 中有嵌套对象或 array 中有对象,它们仍将继续共享相同的引用.

关于javascript - 有人可以解释以下示例中 ...spread 运算符的使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56280494/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com