Redux,标准化实体和lodash合并 [英] Redux, normalised entities and lodash merge

查看:77
本文介绍了Redux,标准化实体和lodash合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Redux,React和Lodash与相当标准的规范化实体存储一起使用.

I'm using Redux, React and Lodash with a fairly standard normalized entities store.

当我在redux reducer中合并新实体时,对我所有现有实体的引用都会更改(尽管未被修改),从而导致任何纯组件都重新呈现.

When I merge in new entities in a redux reducer, the references to all my existing entities change (despite not being modified), causing any pure components to re-render.

是否有lodash合并的替代方法,它可以合并,同时保持对不在合并对象中的值的现有引用?

Is there an alternative to lodash's merge that can merge whilst maintaining the existing references to values that are not in the object being merged in?

let entities = { 
  [1]: {a: true },
  [2]: {a: true, b: true },
}
let response = { 
  [2]: {a: false }
}
let newEntities = _.merge({}, entities, response)

console.log(entities[1] === newEntities[1]) // false

我无法在此处使用Object.assign/ES6 Spread,因为newEntities[2].b将被删除.

I can't use Object.assign/ES6 Spread here as then newEntities[2].b will be deleted.

我确实意识到还有其他解决方案,例如自定义sCU和重新选择,但是在reducer级别上解决此问题要干净得多,而不是必须修改对其道具进行相等性引用检查的每个单个组件,这会更加清洁.

I do realise there are alternative solutions such as custom sCU and reselect, however it would be much cleaner to take care of this at the reducer level rather than having to modify every single component that does an equality reference check on its props.

推荐答案

使用 mergeWith 和自定义程序:

Use mergeWith with a customizer:

let keepRef = (objValue, srcValue) => (
  objValue === undefined ? srcValue : _.mergeWith({}, objValue, srcValue, keepRef)
)
let newEntities = _.mergeWith({}, entities, response, keepRef)

这篇关于Redux,标准化实体和lodash合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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