如何减少React-redux代码的大小?

sasha_nsk3

当我想从商店中连接一些对象时,如何减少代码中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的文章。
谢谢!

Lorefnon

您可以组成选择器功能,并编写自定义钩子。

因此,在上述情况下,您可以执行以下操作:

// 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
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章