我在我的应用程序中使用react,redux和immutablejs.商店是不可变的,并映射到道具.将调度映射到props时,我提供了辅助函数.辅助函数与redux TodoList示例中的这段代码相当:
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch(toggleTodo(id))
}
}
}
我目前遇到的问题是我的纯组件渲染太频繁:上面的连接在每次连接时创建一个onTodoClick函数.
当PureRenderMixin shallow将currentProps与newProps进行比较时,它会将组件标记为shouldUpdate,因为指针已更改.
如何在保持组件的rendercount低的同时在容器中定义辅助函数?
我已经查看了重新选择,但计划仅使用它来计算mapStateToProps中的派生状态.为每个连接创建一个选择器是否更好,所以你的函数也被记忆了?
最佳答案 这可能是一个hack,但您可以根据dispatch参数记住该函数(假设redux总是为同一个商店发送相同的函数):
let lastDispatch;
let dispatchProps;
const mapDispatchToProps = (dispatch) => {
if (!dispatchProps || dispatch !== lastDispatch) {
dispatchProps = {
onTodoClick: (id) => {
dispatch(toggleTodo(id))
}
}
lastDispatch = dispatch;
}
return dispatchProps;
}
或使用lodash memoize:
const mapDispatchToProps = _.memoize((dispatch) => {
return {
onTodoClick: (id) => {
dispatch(toggleTodo(id))
}
}
})
更新:这不是一个黑客,它似乎与他们的官方文档一致:
Note: in advanced scenarios where you need more control over the rendering performance, mapDispatchToProps() can also return a function. In this case, that function will be used as mapDispatchToProps() for a particular component instance. This allows you to do per-instance memoization. You can refer to #279 and the tests it adds for more details. Most apps never need this.