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

Reactjs 如何减少React redux代码的大小?,reactjs,redux,react-hooks,Reactjs,Redux,React Hooks,当我想从我的存储连接几个对象时,如何减少代码中使用选择器的计数? user = useSelector(store => store.user.user, shallowEqual), todos = useSelector(store => store.todos.todos, shallowEqual), id = useSelector(store => store.todos.id, shallowEqual), title = useS

当我想从我的存储连接几个对象时,如何减少代码中使用选择器的计数?

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 MyComponent = () => {
    const {user, todos, ...} = useTodoDetailsSelection();
    // Render components
}

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

因此,在上述场景中,您可以执行以下操作:

// 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 MyComponent = () => {
    const {user, todos, ...} = useTodoDetailsSelection();
    // Render components
}

我认为您可以将其精简为两个
useSelector
钩子,一个用于
user
,一个用于
todos
,只需对
todos
属性、
id
title
等使用普通对象分解即可。我认为您可以将其精简为两个
useSelector
钩子,一个用于
user
,一个用于
todos
,只需对
todos
属性、
id
title
等使用普通对象分解即可。。。