gpt4 book ai didi

reactjs - 如何使用从 createEntityAdapter 生成的 selectById 选择器

转载 作者:行者123 更新时间:2023-12-04 14:35:30 24 4
gpt4 key购买 nike

redux-toolkit 网站上的所有示例都显示了 selectIds 的用法或 selectAll .
使用它们中的任何一个都很简单。我有一个 redux-slice我从哪里导出

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

然后我在我的组件中导入选择器并使用类似
const valueIAmInterestedIn = useSelector(selectUserIds)

我对 selectUserById的用法相关的代码很感兴趣.

最佳答案

根据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使用重新选择创建。

关于reactjs - 如何使用从 createEntityAdapter 生成的 selectById 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62335811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com