Redux状态数组中的更新对象未重新渲染React组件 [英] updating object within redux state array not re-rendering react component

查看:377
本文介绍了Redux状态数组中的更新对象未重新渲染React组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Redux状态下更新Chefs数组中的单个Chef.数组的示例如下:

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' }
  ]

我对API进行了调用,然后向我返回了更新后的Chef对象.我基本上找到了当前状态下的相关Chef对象,但是,当我进行不可变的更新时,我的react组件不会重新渲染.

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.

这是在Redux Reducer中更新对象数组中的单个对象的正确方法吗?

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

推荐答案

您应该从reducer返回新对象,然后可以使用map函数来改进代码

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

这篇关于Redux状态数组中的更新对象未重新渲染React组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆