简体   繁体   English

解构ImmutableJS Map以实现React组件道具

[英]Destructuring ImmutableJS Map for React Component Props

We have a project using React + Redux + ImmutableJS. 我们有一个使用React + Redux + ImmutableJS的项目。 One of our engineers recently added a helper method to support destructuring an ImmutableJS Map when passing it to a component as props: 我们的一位工程师最近添加了一个辅助方法,以支持在将ImmutableJS Map作为prop传递给组件时对其进行破坏:

export function toObjectShallow(mapping: Map) {
    const result = {};
    mapping.map((value, key) => {
        result[key] = value;
    });
    return result;
}

Thus, we can still do the following and avoid being verbose with repeated calls to Map.get : 因此,我们仍然可以执行以下操作,避免重复调用Map.get变得冗长:

<XyzComponent {...toObjectShallow(this.props.xyz)}/>

Yes, that's essentially making two shallow copies (our method + destructuring) of the original object. 是的,这实际上是对原始对象制作两个浅表副本(我们的方法+解构)。 That should be of minimal expense. 那应该是最小的花费。 I'm wondering though, since I don't see this kind of recommendation really anywhere else in the React/Redux/Immutable communities, is there something else I'm missing that would make this unideal? 不过,我想知道,因为我在React / Redux / Immutable社区中的其他地方都没有真正看到这种建议,所以我缺少其他东西吗?

The passed properties are still the original, immutable props. 传递的属性仍然是原始的,不变的道具。 It's just the containing object is mutated which doesn't matter, because it's not getting passed to the component anyways. 只是包含对象发生了变化,这没关系,因为它始终不会传递给组件。 So, what gives? 那么,有什么用呢? This seems like such a simple solution while avoiding toJS() . 避免toJS()时,这似乎是一个简单的解决方案。 Why isn't it really mentioned anywhere? 为什么在任何地方都没有真正提到它?

I followed the advice in the redux docs to use a HOC for all connected components to allow me to interact with plain javascript objects outside of redux. 我遵循redux文档中的建议,对所有连接的组件使用HOC,以允许我与redux之外的普通javascript对象进行交互。 So my selectors and reducers still use ImmutableJS objects, but the rest of the code uses plain javascript objects: 所以我的选择器和缩减器仍然使用ImmutableJS对象,但是其余的代码使用普通的javascript对象:

https://redux.js.org/docs/recipes/UsingImmutableJS.html#use-a-higher-order-component-to-convert-your-smart-components-immutablejs-props-to-your-dumb-components-javascript-props https://redux.js.org/docs/recipes/UsingImmutableJS.html#use-a-higher-order-component-to-convert-your-smart-components-immutablejs-props-to-your-dumb-components- JavaScript的道具

edit- not sure if this is the toJS you are mentioning above, I had assumed you meant ImmutableJS.toJS. 编辑-不确定这是否是您上面提到的toJS,我假设您的意思是ImmutableJS.toJS。

as far as preferences, using an HOC you only need to do it once per component, as opposed to each time you use a component in your method. 就首选项而言,使用HOC只需对每个组件执行一次,而不是每次在方法中使用一个组件。

我认为我正在寻找的“正确”答案是继续使用Immutable JS的toObject() ,该对象将Immutable Map对象转换为常规对象,从而使我们能够继续使用语法糖,同时保持属性不变和不可变必须使用我们自己的浅表副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM