存储中的嵌套数据

存储中的嵌套数据

本文介绍了更新 redux 存储中的嵌套数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 redux 更新存储中嵌套数据数组的最佳/正确方法是什么?

What's the best/correct way to update a nested array of data in a store using redux?

我的商店看起来像这样:

My store looks like this:

{
    items:{
        1: {
            id: 1,
            key: "value",
            links: [
                {
                    id: 10001
                    data: "some more stuff"
                },
                ...
            ]
        },
        ...
    }
}

我有一对异步操作可以更新完整的 items 对象,但我有另一对操作要更新特定的 links 数组.

I have a pair of asynchronous actions that updates the complete items object but I have another pair of actions that I want to update a specific links array.

我的减速器目前看起来像这样,但我不确定这是否是正确的方法:

My reducer currently looks like this but I'm not sure if this is the correct approach:

  switch (action.type) {
    case RESOURCE_TYPE_LINK_ADD_SUCCESS:
      // TODO: check whether the following is acceptable or should we create a new one?
      state.items[action.resourceTypeId].isSourceOf.push(action.resourceTypeLink);
      return Object.assign({}, state, {
        items: state.items,
      });
  }

推荐答案

React 的 update() immutability helper 是一种方便的方式来创建一个普通旧 JavaScript 对象的更新版本而不改变它.

React's update() immutability helper is a convenient way to create an updated version of a plain old JavaScript object without mutating it.

你给它一个要更新的源对象和一个描述需要更新的部分的路径和需要进行的更改的对象.

You give it the source object to be updated and an object describing paths to the pieces which need to be updated and changes that need to be made.

例如,如果一个操作具有 idlink 属性,并且您想将 link 推送到键控项目中的链接数组使用 id:

e.g., if an action had id and link properties and you wanted to push the link to an array of links in an item keyed with the id:

var update = require('react/lib/update')

// ...

return update(state, {
  items: {
    [action.id]: {
      links: {$push: action.link}
    }
  }
})

(示例为 action.id 使用 ES6 计算属性名称)

(Example uses an ES6 computed property name for action.id)

这篇关于更新 redux 存储中的嵌套数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 08:14