如何在 redux 上使用 reselect 获取 ownProps?

How can I get ownProps using reselect on redux?

我想使用基于 mapStateToPropsownProps 的重新选择来创建带有记忆的选择器。

您可以使用 react-redux 提供的 connect 方法将选择器连接到组件,然后将组件属性 (ownProps) 作为第二个参数传递给选择器。

container.js

import { connect } from 'react-redux';
import { getVisibleTodos } from './selectors';

...

const mapStateToProps = (state, props) => {
  return {
    todos: getVisibleTodos(state, props),
  };
};

const VisibleTodoList = connect(
  mapStateToProps,
)(TodoList);

export default VisibleTodoList;

然后您可以在选择器中访问这些道具

selectors.js

import { createSelector } from 'reselect';

const getVisibilityFilter = (state, props) =>
  state.todoLists[props.listId].visibilityFilter;

const getTodos = (state, props) =>
  state.todoLists[props.listId].todos;

const getVisibleTodos = createSelector(
  ...
);

export default getVisibleTodos;

However, this will not memoize correctly if you have multiple instances of the component you're passing props from. In that case, the selector would receive a different props argument each time, so it would always recompute instead of returning a cached value.

要在传递 props 保留记忆的同时跨多个组件共享选择器,组件的每个实例都需要自己的选择器私有副本。

您可以通过创建一个函数来做到这一点,每次调用时 returns 选择器的一个新副本。

selectors.js

import { createSelector } from 'reselect';

const getVisibilityFilter = (state, props) =>
  state.todoLists[props.listId].visibilityFilter;

const getTodos = (state, props) =>
  state.todoLists[props.listId].todos;

const makeGetVisibleTodos = () => {
  return createSelector(
    ...
  );
}

export default makeGetVisibleTodos;

如果提供的 mapStateToProps 参数连接 returns 一个函数而不是一个对象,它将用于为每个实例创建一个单独的 mapStateToProps 函数容器。

考虑到这一点,您可以创建一个函数 makeMapStateToProps 来创建一个新的 getVisibleTodos 选择器,并且 returns 一个 mapStateToProps 函数可以独占访问新选择器:

import { connect } from 'react-redux';
import { makeGetVisibleTodos } from './selectors';

...

const makeMapStateToProps = () => {
  const getVisibleTodos = makeGetVisibleTodos();
  const mapStateToProps = (state, props) => {
    return {
      todos: getVisibleTodos(state, props),
    };
  };
  return mapStateToProps;
};

const VisibleTodoList = connect(
  makeMapStateToProps,
)(TodoList);

export default VisibleTodoList;

现在 VisibleTodosList 容器的每个实例都将获得自己的 mapStateToProps 函数和私有 getVisibleTodos 选择器。无论容器的渲染顺序如何,记忆现在都可以正常工作。


这改编自 (公然复制) 来自 Reselect documentation