【问题标题】:React: Decrease action causes undefined state in Redux reducerReact:减少操作导致 Redux 减速器中的未定义状态
【发布时间】:2020-03-27 22:40:08
【问题描述】:

我正在使用 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 似乎是未定义的。

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

【问题讨论】:

    标签: javascript reactjs redux state bind


    【解决方案1】:

    看起来变量i 没有在你的reducers switch 语句的DECREASE_LIKES 的范围内定义。因此,这将导致 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;
      }
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多