gpt4 book ai didi

reactjs - Redux - 每次使用新变量在 reducer switch 语句中定义新状态?

转载 作者:行者123 更新时间:2023-12-03 14:09:11 25 4
gpt4 key购买 nike

我的 reducer 看起来像这样:

switch (action.type) {
case "UPDATE_CURRENT_USER":
let newState = {...state, ...action.payload };
return newState;
case "GET_CURRENT_USER":
return state;
case "UPDATE_USERNAME":
newState = {...state, name: action.payload.name};
return state;
}

现在,我第二次使用 newState 时,我不再定义它。我只是使用上面定义的变量。这个可以吗?我想重新定义它,但出现错误。但我不确定这种方式是否仍然会给我正确的结果 - 尽管一切似乎都工作正常?

最佳答案

使用大括号{}在case语句内创建新的 block 作用域:

switch (action.type) {
case "UPDATE_CURRENT_USER": {
let newState = {...state, ...action.payload };
return newState;
}
case "GET_CURRENT_USER":
return state;
case "UPDATE_USERNAME": {
let newState = {...state, name: action.payload.name};
return newState;
}
}

由于 letconst 是 block 作用域的局部变量,因此它们仅在当前 block 中可见。

我的代码您正在使用未声明的 newState 变量:

switch (action.type) {
case "UPDATE_CURRENT_USER":
// (conditionaly) declaring block scoped variable newState
let newState = {...state, ...action.payload };
return newState;
case "UPDATE_USERNAME":
// here you cannot declare newState variable because it might be declared before
// however the variable is not declared since we are in other case
// so that here you are using global window variable window.newState
newState = {...state, name: action.payload.name};
return state;
}

关于reactjs - Redux - 每次使用新变量在 reducer switch 语句中定义新状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44433968/

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