Redux - 每次使用新变量在减速器 switch 语句中定义新状态?

Geo*_*der 3 flux reactjs redux react-redux

我的减速机看起来像这样:

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;
  }
Run Code Online (Sandbox Code Playgroud)

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

mad*_*ox2 5

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

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

我的代码您正在使用未声明的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;
}
Run Code Online (Sandbox Code Playgroud)