当我想连接商店中的几个对象时,如何在代码中减少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);
如果对你来说不是太痛苦,给我写一些关于 react、redux 或 react-redux 的好书。
谢谢!
您可以编写选择器函数,并编写自定义钩子。
因此,在上述场景中,您可以执行以下操作:
// 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;
}
或者,如果您发现自己在多个组件中一次又一次地组合同一组选择器,请在自定义钩子中提取整个内容:
const useTodoDetailsSelection = () => ({
user: useSelector(store => store.user.user, shallowEqual),
todos: useSelector(store => store.todos.todos, shallowEqual),
...
})
现在在组件中使用该钩子:
const MyComponent = () => {
const {user, todos, ...} = useTodoDetailsSelection();
// Render components
}