Aks*_*hay 3 reactjs redux react-redux redux-toolkit
redux-toolkit 网站上的所有示例都显示了selectIds或 的用法selectAll。使用它们中的任何一个都很简单。我有一个redux-slice我要出口的地方
export const {
selectById: selectUserById,
selectIds: selectUserIds,
selectEntities: selectUserEntities,
selectAll: selectAllUsers,
selectTotal: selectTotalUsers
} = usersAdapter.getSelectors(state => state.users)
Run Code Online (Sandbox Code Playgroud)
然后我在我的组件中导入选择器并使用类似
const valueIAmInterestedIn = useSelector(selectUserIds)
Run Code Online (Sandbox Code Playgroud)
我对与selectUserById.
HMR*_*HMR 11
根据文档,by id 选择器具有以下签名:selectById: (state: V, id: EntityId) => T | undefined.
因此,您可以通过以下方式在组件中调用它:
const Component = ({ id }) => {
const item = useSelector((state) =>
selectUserById(state, id)
);
};
Run Code Online (Sandbox Code Playgroud)
如果您对服务器上的实体进行排序/过滤,这种“规范化”的实现可能不起作用,因为状态看起来更像是:
{
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 },
},
},
},
};
Run Code Online (Sandbox Code Playgroud)
我没有与“助手”一起工作,所以必须研究它,因为它可能有助于服务器端过滤和排序。
我也怀疑它会记住选择器:
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)
);
});
Run Code Online (Sandbox Code Playgroud)
我创建了一个关于如何使用通过 reselect 创建的选择器的简短文档。
| 归档时间: |
|
| 查看次数: |
3471 次 |
| 最近记录: |