updating object within redux state array not re-re

2019-08-18 07:05发布

问题:

This question already has an answer here:

  • My Redux state has changed, why doesn't React trigger a re-render? 1 answer

I am trying to update a single chef within the chefs array in my redux state. An example of the array is as follows:

  [
    { _id: 1, name: 'first chef' },
    { _id: 2, name: 'second chef' },
    { _id: 2, name: 'third chef' }
  ]

I make a call to the API which then returns me the updated chef object. I basically find the related chef object in my current state, however, when I immutably update it, my react component doesn't re-render.

Is this the correct way to update a single object within a array of objects in a redux reducer?

import _ from 'lodash';
import { ADMIN_LIST_CHEFS, ADMIN_GET_CHEF, UPDATE_CHEF_LIST } from '../actions/types';

const INITIAL_STATE = { chefs: [], chef: null };
let CHEFS = [];
let INDEX = null;

export default function (state = INITIAL_STATE, action) {
  switch (action.type) {
    case UPDATE_CHEF_LIST:
      CHEFS = state.chefs;
      INDEX = _.findIndex(CHEFS, (chef => chef._id === action.id));
      state.chefs.splice(INDEX, 1, action.payload);
      return { ...state };
    default:
      break;
  }
  return state;
}

回答1:

You should return new object from your reducer and you can improve your code with map function

export default function (state = INITIAL_STATE, action) {
  switch (action.type) {
    case UPDATE_CHEF_LIST:
      return {
        ...state,
        chefs: state.chefs.map( chef => chef._id === action.id? action.payload: chef)
      }
    default:
      break;
  }
  return state;
}