updating object within redux state array not re-rendering react component [duplicate]

对着背影说爱祢 提交于 2019-12-12 04:43:20

问题


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


来源:https://stackoverflow.com/questions/46893279/updating-object-within-redux-state-array-not-re-rendering-react-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!