简体   繁体   中英

React: Decrease action causes undefined state in Redux reducer

I am using Redux to implement a basic Like counter in this project / Example

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

This is the following code used to manage the likes states increase:

Action

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

Reducer

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

Component

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

Now i want to add as exercise a decrease function to manage the decrease state likes , and here where the issue comes from.

See the code:

Action

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

Reducer => Added DECREASE_LIKES case

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

Component

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

While I am debugging it looks like that in the DECREASE case the state is undefined.

What am i doing wrong? How can i fix it?

It looks like the variable i is not defined in scope of the DECREASE_LIKES case of your reducers switch statement. This will therefore cause the logic of the DECREASE_LIKES reduction to producue incorrect results.

Consider making the following adjustments to your reducer to resolve the issue:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM