【发布时间】:2016-09-12 20:42:04
【问题描述】:
示例代码:https://github.com/d6u/example-redux-update-nested-props/blob/master/one-connect/index.js
观看现场演示:http://d6u.github.io/example-redux-update-nested-props/one-connect.html
如何优化嵌套组件props的小更新?
我有上述组件,Repo 和 RepoList。我想更新第一个 repo 的标签 (Line 14)。所以我发送了一个UPDATE_TAG 操作。在我实现 shouldComponentUpdate 之前,调度需要大约 200 毫秒,这是意料之中的,因为我们浪费了很多时间来区分没有改变的 <Repo/>s。
添加shouldComponentUpdate后,dispatch大约需要30ms。在生产构建 React.js 之后,更新只花费了大约 17 毫秒。这好多了,但是 Chrome 开发控制台中的时间线视图仍然显示卡顿帧(超过 16.6 毫秒)。
想象一下,如果我们有很多这样的更新,或者<Repo/> 比当前更复杂,我们将无法保持 60fps。
我的问题是,对于嵌套组件的 props 进行如此小的更新,是否有更有效和规范的方式来更新内容?我还能使用 Redux 吗?
我得到了一个解决方案,将每个 tags 替换为一个可观察的内部减速器。类似的东西
// inside reducer when handling UPDATE_TAG action
// repos[0].tags of state is already replaced with a Rx.BehaviorSubject
get('repos[0].tags', state).onNext([{
id: 213,
text: 'Node.js'
}]);
然后我使用https://github.com/jayphelps/react-observable-subscribe 在 Repo 组件中订阅它们的值。这很好用。即使使用 React.js 的开发版本,每次调度也只需 5 毫秒。但我觉得这是 Redux 中的一种反模式。
更新 1
我遵循了 Dan Abramov 的回答和 normalized my state 和 updated connect components 中的建议
新的状态形状是:
{
repoIds: ['1', '2', '3', ...],
reposById: {
'1': {...},
'2': {...}
}
}
我在ReactDOM.render 周围添加了console.time 到时间the initial rendering。
但是,性能比以前更差(初始渲染和更新)。 (来源:https://github.com/d6u/example-redux-update-nested-props/blob/master/repo-connect/index.js,现场演示:http://d6u.github.io/example-redux-update-nested-props/repo-connect.html)
// With dev build
INITIAL: 520.208ms
DISPATCH: 40.782ms
// With prod build
INITIAL: 138.872ms
DISPATCH: 23.054ms
我认为每个<Repo/> 上的连接都有很多开销。
更新 2
根据 Dan 的更新答案,我们必须返回 connect 的 mapStateToProps 参数,而不是返回一个函数。你可以看看丹的答案。我还更新了the demos。
下面,我的电脑上的性能要好得多。而且只是为了好玩,我还在我谈到的减速器方法中添加了副作用(source,demo)(真的不要使用它,它只是为了实验)。
// in prod build (not average, very small sample)
// one connect at root
INITIAL: 83.789ms
DISPATCH: 17.332ms
// connect at every <Repo/>
INITIAL: 126.557ms
DISPATCH: 22.573ms
// connect at every <Repo/> with memorization
INITIAL: 125.115ms
DISPATCH: 9.784ms
// observables + side effect in reducers (don't use!)
INITIAL: 163.923ms
DISPATCH: 4.383ms
更新 3
刚刚添加了react-virtualized example,基于“记忆连接”
INITIAL: 31.878ms
DISPATCH: 4.549ms
【问题讨论】:
-
我修改了答案。
-
示例链接已失效:/
标签: javascript reactjs redux react-redux