gpt4 book ai didi

reactjs - eslint : no-case-declaration - unexpected lexical declaration in case block

转载 作者:行者123 更新时间:2023-12-03 12:57:01 29 4
gpt4 key购买 nike

在 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 } };

ESLint 不喜欢在 reducer 内的 case block 内使用 let 语句,得到:

eslint: no-case-declaration - unexpected lexical declaration in case block

最佳答案

ESLint doesn't like let statements inside case blocks inside areducer, Why?

不鼓励这样做,因为它会导致变量处于当前case范围之外。通过使用 block ,您可以将变量的范围限制在该 block 内。

使用 {} 创建带有大小写的 block 作用域,如下所示:

case DELETE_INTEREST: {
let .....
return (...)
}

检查此片段:

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();

要从数组中删除元素,请使用 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 } };

关于reactjs - eslint : no-case-declaration - unexpected lexical declaration in case block,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50752987/

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