在reducer中更新状态的更好方法是什么?
case DELETE_INTEREST:
let deleteInterests = state.user.interests;
let index = deleteInterests.findIndex(i => i == action.payload);
deleteInterests.splice(index, 1);
return { ...state, user: { ...state.user, interests: deleteInterests } };
Run Code Online (Sandbox Code Playgroud)
ESLint不喜欢在reducer中的case块内部使用let语句,得到:
eslint:no-case-declaration - case块中的意外词法声明
May*_*kla 63
ESLint不喜欢let语句块里面的let语句,为什么?
使用{}
来创建情况下,块范围,就像这样:
case DELETE_INTEREST: {
let .....
return (...)
}
Run Code Online (Sandbox Code Playgroud)
检查此代码段:
function withOutBraces() {
switch(1){
case 1:
let a=10;
console.log('case 1', a);
case 2:
console.log('case 2', a)
}
}
function withBraces() {
switch(1){
case 1: {
let a=10;
console.log('case 1', a);
}
case 2: {
console.log('case 2', a)
}
}
}
console.log('========First Case ============')
withOutBraces()
console.log('========Second Case ============')
withBraces();
Run Code Online (Sandbox Code Playgroud)
要从数组中删除元素,请使用array.filter,因为splice将对原始数组进行更改.写这样:
case DELETE_INTEREST:
let deleteInterests = state.user.interests;
let newData = deleteInterests.filter(i => i !== action.payload);
return { ...state, user: { ...state.user, interests: newData } };
Run Code Online (Sandbox Code Playgroud)
小智 27
尝试用 {} 封装内部,就像这个看起来简单的例子
case EnumCartAction.DELETE_ITEM: {
const filterItems = state.cart.filter((item) => item._id !== action.payload)
return {
...state,
cart: filterItems
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7491 次 |
最近记录: |