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

时间:2017-06-08 11:04:58

标签: reactjs redux react-redux flux

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

.as-console-wrapper { max-height: 100% !important; top: 0; }

现在,我第二次使用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; } 我没有再次定义它。我只是使用我上面定义的变量。这个可以吗? 我想重新定义它,但得到了一个错误。但我不确定这种方式是否仍会给我正确的结果 - 虽然一切似乎都运转良好?

2 个答案:

答案 0 :(得分:3)

使用花括号{}在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;
  }
}

由于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;
}

答案 1 :(得分:0)

您不需要为新状态创建变量,为其赋值并返回它。相反,您可以立即返回新的状态值。并且不要忘记在最后添加默认案例。

switch (action.type) {
        case 'UPDATE_CURRENT_USER':
          return { ...state, ...action.payload };
        case 'GET_CURRENT_USER':
          return state;
        case 'UPDATE_USERNAME':
          return { ...state, name: action.payload.name };
        default:
          return state;
      }