究竟是什么意思是这三个点以及为什么我需要它们?
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 )
}
}
Run Code Online (Sandbox Code Playgroud)
Wer*_*son 38
这三个点被称为Typescript 的扩展运算符(也来自ES7).
spread运算符返回数组的所有元素.就像你将分别编写每个元素一样:
let myArr = [1, 2, 3];
return [1, 2, 3];
//is the same as:
return [...myArr];
Run Code Online (Sandbox Code Playgroud)
这主要是语法糖,因为它汇编了这个:
func(...args);
Run Code Online (Sandbox Code Playgroud)
对此:
func.apply(null, args);
Run Code Online (Sandbox Code Playgroud)
在你的情况下,这将编译为:
return [...state, action.payload];
//gets compiled to this:
return state.concat([action.payload]);
Run Code Online (Sandbox Code Playgroud)
Shw*_*eta 30
它是一个扩展运算符 (...),用于扩展数组/对象的元素或用于从另一个数组或对象初始化数组或对象。
让我们从现有数组创建新数组来理解这一点。
让 Array1 = [ 1, 2, 3]; //1,2,3
让 Array2 = [ 4, 5, 6]; //4,5,6
//从现有数组创建新数组
让 copyArray = [...Array1]; //1,2,3
//合并两个数组创建数组
让合并数组 = [...Array1, ...Array2]; //1,2,3,4,5,6
//从现有数组+更多元素创建新数组
让 newArray = [...Array1, 7, 8]; //1,2,3,7,8
| 归档时间: |
|
| 查看次数: |
11951 次 |
| 最近记录: |