5

Right now I'm using reselect to create my selectors to extract data from the store and pass it to the props via connect. For simplicity, the result of my selectors is always a JS object (calling toJS() at the end of the selector), something like this:

const selector = state => state.get('data').toJS();

Now I'm trying to improve some performance and I realized that shouldComponentUpdate shallow comparison loses the advantages of immutability because of the way I'm returning from my selectors.

On the other hand, using .get('prop') inside my html seems extremely annoying:

<div>{this.props.data.get('prop')}</div>

Especially if I have a case of passing a simple JS object to a child component which is mutable, like this:

<ChildComponent totalItems={10} />

And then there is no consistency when accessing the props (some are mutable and some are immutable).

I thought of creating an helper unwrap function, something like this:

const unwrap = obj => obj && obj.toJS ? obj.toJS() : obj;

But I don't really like this solution.. I don't really like any of those approaches.

What do you use for both clean code & performance?

4

3 回答 3

2

将 props 传递给组件将键下的所有数据收集为不可变的。

<MyComponent propsKey={Immutable.fromJS({someData: {key: "value"}})} />

要使用不可变的好处,您应该避免使用 toJS()。这是非常昂贵的,你不能使用有用的不可变函数。在达到“价值”之前,您应该使用 Immutable.get()。起初它很烦人,但你可以及时看到它是如何有用和易于使用的。(使用 getIn() 获取内部键可能比链 get 函数更烦人)。通过这种方式,您的代码可以更高效地工作,并且您不需要使用 unwrap 函数,在您的组件中,您可以保证 this.props.propsKey 下的数据始终不可变。

于 2016-08-22T18:55:44.783 回答
1

您应该将您的展示组件包装在一个简单的高阶组件中,该组件调用toJS()任何传递给它的 Immutable.js 对象道具。

这将为您提供保持 Immutable.js 的性能优势,同时防止容器组件重新渲染过多,以及保持您的展示组件无依赖,因此易于重用和可测试的最佳平衡。

Redux 文档为使用 Immutable.js 提供了很好的最佳实践选择,特别是,何时不使用.toJS()为什么你的表现组件应该保持纯净,以及如何定义和使用“toJS”高阶组件

于 2017-08-29T14:17:45.983 回答
0

一年半后用我自己的答案回到我的问题:

如果可能,请始终传递不可变对象。如果它不是不可变的,就按原样传递它。

我认为性能比代码的漂亮程度重要得多。

如果一个值是不可变的或可变的,我会按原样传递它,如果不需要,则永远不要调用toJSfromJS如果可变值没有存储在 redux 存储中,我也不会包装它们。

我只需要在子组件内部意识到一些道具是不可变的,而有些则不是——实际上它非常简单,因为几乎总是一个复杂的对象是不可变的。

于 2018-03-18T13:03:54.073 回答