[英]How I can reduce the size of the React-redux code?
How i can reduce count of useSelector , in my code, when I want to connect a few objects from my store?当我想连接商店中的一些对象时,如何减少代码中useSelector的数量?
user = useSelector(store => store.user.user, shallowEqual),
todos = useSelector(store => store.todos.todos, shallowEqual),
id = useSelector(store => store.todos.id, shallowEqual),
title = useSelector(store => store.todos.title, shallowEqual),
deadline = useSelector(store => store.todos.deadline, shallowEqual),
status = useSelector(store => store.todos.status, shallowEqual),
isOpen = useSelector(store => store.todos.showPopUp, shallowEqual);
If it's not too painful for you, write me some good books to read about react, redux, or react-redux together.如果对您来说不是太痛苦,请给我写一些关于 React、redux 或 react-redux 的好书。
Thanks!谢谢!
You can compose selector functions, and write custom hooks.您可以编写选择器函数,并编写自定义挂钩。
So in above scenario, you can do:因此,在上述情况下,您可以执行以下操作:
// selectors.js (selectors shared across files)
const selectUser = store => store.user.user;
const selectTodos = store => store.todos.todos;
// Now in your component:
const [user, todos, ...] = useSelector(store => [
selectUser,
selectStore,
...
].map(f => f(store)), shallowCompareArrayMembers);
// (Feel free to alternatively use object destructuring either).
// Where shallowCompareArrayMembers is a custom comparator to lift shallowEqual over an array:
const shallowCompareArrayMembers = (prev, next) => {
if (prev.length !== next.length) {
throw new Error('Expected array lengths to be same');
}
for (let i = 0; i < prev.length; i++) {
if (!shallowEqual(prev[i], next[i])) return false;
}
return true;
}
Alternatively, if you find yourself combining same set of selector again and again in multiple components, extract out the whole thing in a custom hook:或者,如果您发现自己在多个组件中一次又一次地组合同一组选择器,请在自定义挂钩中提取整个内容:
const useTodoDetailsSelection = () => ({
user: useSelector(store => store.user.user, shallowEqual),
todos: useSelector(store => store.todos.todos, shallowEqual),
...
})
Now use that hook in component:现在在组件中使用该钩子:
const MyComponent = () => {
const {user, todos, ...} = useTodoDetailsSelection();
// Render components
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.