角度 这三个点在@NGRX中是什么意思



这三个点到底意味着什么,为什么我需要它们?

export function leadReducer(state: Lead[]= [], action: Action {
    switch(action.type){
        case ADD_LEAD:
            return [...state, action.payload];
        case REMOVE_LEAD:
            return state.filter(lead => lead.id !== action.payload.id )
}
}

这三个点被称为打字稿的传播算子(也来自ES7)。

传播操作员返回数组的所有元素。就像您会单独写下每个元素一样:

let myArr = [1, 2, 3];
return [1, 2, 3];
//is the same as:
return [...myArr];

这主要只是句法糖,因为它会汇编以下内容:

func(...args);

func.apply(null, args);

在您的情况下,这将被汇编为:

return [...state, action.payload];
//gets compiled to this:
return state.concat([action.payload]);

它是一个传播操作员(...),用于传播数组/对象的元素或从其他数组或对象

让我们从现有数组中创建新数组以了解这一点。

让array1 = [1,2,3];//1,2,3

让array2 = [4,5,6];//4,5,6

//从现有数组创建新数组

让copyArray = [... array1]; //1,2,3

//通过合并两个数组

创建数组

让MergedArray = [... array1,... array2];//1,2,3,4,5,6

//从现有数组 更多元素

创建新数组

让newarray = [... array1,7,8];//1,2,3,7,8

... ever operator )通过将每个值从索引0返回到索引length-1

来起作用。

上下文:在使用子阵列(或任何其他第二层属性)。

查找:注意嵌套数组(或子专业)不是按值而而是参考传递。换句话说,仅作为"按价值"的副本传递的第一级项目。请参阅示例:

sourceArray = [ 1, [2, 3] ] // Second element is a sub-array
targetArray = [ ...sourceArray]
console.log("Target array result:", JSON.stringify(targetArray), "nn") //it seems a copy, but...
console.log("Let's update the first source value:n")
sourceArray[0] = 10
console.log("Updated source array:", JSON.stringify(sourceArray), "n")
console.log("Target array is NOT updated, It keeps a copy by value:")
console.log(JSON.stringify(targetArray), "nn")
//But if you update a value of the sub-array, it has NOT been copied
console.log("Finally, let's update a nested source value:n")
sourceArray[1][0] = 20
console.log("Updated source nested array:", JSON.stringify(sourceArray), "n")
console.log("Target array is updated BY REFERENCE! ", )
console.log(JSON.stringify(targetArray), "nn") // it is not a copy, it is a reference!
console.log("CONCLUSION: ... spread syntax make a copy 'by value' for first level elements, but 'by reference' for second level elements (This applies also for objects) so take care!n")

最新更新