在 react redux reducer 中更新数组中的对象获取 map() 不是函数 [英] Updating an object within array in react redux reducer getting map() is not a function

查看:35
本文介绍了在 react redux reducer 中更新数组中的对象获取 map() 不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当复杂/嵌套的 redux 存储,如下所示:

I have a fairly complex/nested redux store like this:

{
  object1
  {
    array:
    [
      object[1]: {
        id: 1,
        replace: ""
      }
      object[2]: {
        id: 2
        replace: ""
      }
      object[3]: {
        id: 3,
        replace: ""
      }
    ]
  }
}

在调度动作后,我需要根据 ID 将动作插入到 object[] 之一.我目前正在使用以下脚本来更新减速器中的 replace.但是,由于 object2: {} 的大括号,这会将数组更改为对象.

After dispatching an action, I need to insert the action to one of the object[] based on ID. I am currently using the following scripts to update replace within the reducer. However this will change the array to an object due to the curly bracket of object2: {}.

case UPDATE:
  return {
    ...state,
    object1: {
      ...state.object1,
      array: {
        ...state.object1.array,
        [action.id]: {
          ...state.object1.array[action.id],
          replace: action.result
        }
      }
    }
  };

在那之后我的渲染会中断,因为 object2.map 在更改为 object 后不再是一个函数.如何在不将其转换为对象的情况下解决此问题?

My render will breaks after that since object2.map is no longer a function after changing to object. How do I workaround this without converting it to an object?

以下将因语法错误而失败:

The following will failed with syntax error:

case UPDATE:
  return {
    ...state,
    object1: {
      ...state.object1,
      array: [
        ...state.object1.array,
        [action.id]: {
          ...state.object1.array[action.id],
          replace: action.result
        }
      ]
    }
  };

推荐答案

不能直接用spread语法指定要修改的索引,需要先找到索引然后像

You cannot directly specify the index that you want to modify with spread syntax, you need to first find the index and do it like

case UPDATE:
  var idx = state.object1.object2.findIndex(obj => obj.id === action.id)
  return {
    ...state,
    object1: {
      ...state.object1,
      object2: [
        ...state.object1.object2.slice(0, idx),
        {
            ...state.object1.object2[idx],
            replace: action.result 
        }
        ...state.object1.object2.slice(idx + 1)
      ]
    }
  };

或者你可以使用 immutability-helper 包.有关如何操作的示例,请参阅此答案

Or else you can make use of immutability-helper package. See this answer for a sample of how to do it

如何使用不变性助手更新数组中的嵌套对象?

这篇关于在 react redux reducer 中更新数组中的对象获取 map() 不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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