reactjs - 在智能容器中定义函数时如何保持组件的纯粹性?

标签 reactjs redux

我在我的应用程序中使用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.

参见:https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options

关于reactjs - 在智能容器中定义函数时如何保持组件的纯粹性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39231731/

相关文章:

node.js - 部署到heroku后,后端的req.query在React前端变成了json,如何修复?

javascript - 如何监听 react hooks 中的 redux 状态变化?

javascript - 添加数据后从 Redux Store 获取数据

reactjs - Docker-Compose 用于 react 和 flask 使用 docker-compose up 执行容器

android - 使用 react-native-firebase 编译 react-native

javascript - 如何禁用所有 typescript 类型检查?

reactjs - 组织数百个组件的最佳实践?

javascript - React JS 中在特定 Prop 更改时调用组件方法的正确模式是什么?

redux - 将 redux 与 aws-appsync 集成

javascript - 在 React 中处理多个输入