【问题标题】:How I can reduce the size of the React-redux code?如何减少 React-redux 代码的大小?
【发布时间】:2020-10-17 18:16:38
【问题描述】:

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

【问题讨论】:

  • 我认为你可以将其精简到只有两个 useSelector 钩子,一个用于 user,一个用于 todos,并且只需对 todos 属性使用普通对象解构,@987654326 @、title 等...

标签: reactjs redux react-hooks


【解决方案1】:

您可以编写选择器函数,并编写自定义钩子。

所以在上述情况下,你可以这样做:

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

【讨论】:

    猜你喜欢
    • 2021-08-29
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    相关资源
    最近更新 更多