我在我的应用程序中使用react、redux 和immutablejs。 store 是不可变的,并且映射到 props。当将调度映射到 props 时,我提供了辅助函数。辅助函数与 redux TodoList 示例中的这段代码类似:
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch(toggleTodo(id))
}
}
}
我当前遇到的问题是我的纯组件渲染过于频繁:上面的连接每次连接都会创建一个 onTodoClick
函数。
当 PureRenderMixin 将 currentProps 与 newProps 进行浅比较时,它会将组件标记为 shouldUpdate,因为指针已更改。
如何在容器中定义辅助函数,同时保持组件的渲染计数较低?
我已经研究过重新选择,但计划仅将其用于计算 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.
关于reactjs - 在智能容器中定义函数时如何保持组件的纯粹性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39231731/