React:减少操作导致 Redux reducer 中的未定义状态

React: Decrease action causes undefined state in Redux reducer

我正在使用 Redux 在这个项目/示例中实现一个基本的 Like 计数器

https://codesandbox.io/s/github/mralwin/Reduxstagram

这是下面用来管理点赞状态增加的代码:

动作

export function increment(index) {
  return {
    type: "INCREMENT_LIKES",
    index
  };
}

减速器

function posts(state = [], action) {
  switch (action.type) {
    case "INCREMENT_LIKES":
      const i = action.index;
      return [
        ...state.slice(0, i), // before the one we are updating
        { ...state[i], likes: state[i].likes + 1 },
        ...state.slice(i + 1) // after the one we are updating
      ];
    default:
      return state;
  }
}

组件

<button onClick={this.props.increment.bind(null, i)} className="likes">

现在我想添加一个减少功能作为练习来管理减少喜欢的状态,这里是问题的来源。

见代码:

动作

export function decrease(index) {
  return {
    type: 'DECREASE_LIKES',
    index: i
  };
}

Reducer => 添加了DECREASE_LIKES案例

function rooms(state = [], action) {
  switch (action.type) {
    case 'INCREMENT_LIKES' :
      const i = action.index;
      return [
        ...state.slice(0, i),
        {...state[i], likes: state[i].likes + 1 },
        ...state.slice(i + 1)
      ];
    case 'DECREASE_LIKES' :
      return [
        ...state.slice(0, i),
        {...state[i], likes: state[i].likes - 1 },
        ...state.slice(i + 1)
      ];
    default:
      return state;
  }
}

组件

<button onClick={this.props.decrease.bind(null, i)} className="likes">

虽然我正在调试,但在 DECREASE 情况下,state 未定义。

我做错了什么?我该如何解决?

看起来变量 i 没有定义在你的 reducers switch 语句的 DECREASE_LIKES case 的范围内。因此,这将导致 DECREASE_LIKES 减少的逻辑产生不正确的结果。

考虑对您的减速器进行以下调整以解决该问题:

function rooms(state = [], action) {
  switch (action.type) {
    case 'INCREMENT_LIKES' : {
      const i = action.index;
      return [
        ...state.slice(0, i),
        {...state[i], likes: state[i].likes + 1 },
        ...state.slice(i + 1)
      ];
    }
    case 'DECREASE_LIKES' : {
      // Use a different variable for visual distinction/clarity
      const j = action.index;

      // Use j from action index in reduction logic for this action
      return [
        ...state.slice(0, j),
        {...state[j], likes: state[j].likes - 1 },
        ...state.slice(j + 1)
      ];
    }
    default:
      return state;
  }
}