【问题标题】:How to use selectById selector generated from createEntityAdapter如何使用从 createEntityAdapter 生成的 selectById 选择器
【发布时间】:2020-10-01 18:30:44
【问题描述】:

redux-toolkit 网站上的所有示例都显示了 selectIdsselectAll 的用法。 使用它们中的任何一个都很简单。我有一个 redux-slice 我正在导出的地方

export const {
  selectById: selectUserById,
  selectIds: selectUserIds,
  selectEntities: selectUserEntities,
  selectAll: selectAllUsers,
  selectTotal: selectTotalUsers
} = usersAdapter.getSelectors(state => state.users)

然后我在我的组件中导入选择器并使用 like

const valueIAmInterestedIn = useSelector(selectUserIds)

我对@9​​87654326@的用法相关的代码感兴趣。

【问题讨论】:

    标签: reactjs redux react-redux redux-toolkit


    【解决方案1】:

    根据documentation,by id 选择器具有以下签名:selectById: (state: V, id: EntityId) => T | undefined

    所以你可以通过以下方式在你的组件中调用它:

    const Component = ({ id }) => {
      const item = useSelector((state) =>
        selectUserById(state, id)
      );
    };
    

    如果您在服务器上对实体进行排序/过滤,这种“规范化”实现可能不起作用,因为状态看起来更像:

    {
      data: {
        entityType: {
          //query is key and value is status and result
          //  of the api request
          'sort=name&page=1': {
            loading: false,
            requested: true,
            error: false,
            stale: false,
            ids: [1, 2],
          },
          'sort=name:desc&page=1': {
            //would have loading, requested ....
            ids: [2, 1],
          },
          data: {
            //all the data (fetched so far)
            '1': { id: 1 },
            '2': { id: 2 },
          },
        },
      },
    };
    

    我没有使用过“助手”,因此必须对其进行研究,因为它可能有助于服务器端过滤和排序。

    我也怀疑它会记住选择器:

    const List = ({ items }) => (
      <ul>
        {items.map(({ id }) => (
          <Item key={id} id={id} />
        ))}
      </ul>
    );
    const Item = React.memo(function Item({ id }) {
      //selectUserById is called with different id during
      // a render and nothing will be memoized
      const item = useSelector((state) =>
        selectUserById(state, id)
      );
    });
    

    我创建了一个简短的文档,介绍如何使用通过重新选择创建的selectors

    【讨论】:

      【解决方案2】:

      可以在selectById 之上创建选择器,如下所示:

      export const getLanguageById = (entityId: number) => {
        return createSelector(selectLanguageState, (state) =>
          selectById(state, entityId)
        );
      };
      

      这可以在您的组件中使用,如下所示:

      const language = useSelector(languageSelectors.getLanguageById(18));
      

      我想它更直接,更容易阅读/理解。

      谢谢, 马尼什

      【讨论】:

        猜你喜欢
        • 2020-11-07
        • 2011-06-12
        • 2022-06-17
        • 2015-05-31
        • 2019-10-12
        • 1970-01-01
        • 1970-01-01
        • 2023-04-08
        相关资源
        最近更新 更多