如何将减速减速器与CombineReducers一起使用

时间:2018-10-24 11:15:47

标签: javascript reactjs redux reduce reducers

因此,我正在尝试在另一个reducer中使用一个reducer的某种状态,而我正在寻找一种解决方案,看来软件包reduce-reducers确实做到了,但这是我的问题...

我有以下rootReducer.js文件,我在其中导入所有的减速器,并与combineReducers合并,如下所示……

import { combineReducers } from "redux";
import globalReducer from "./globalReducer";
import booksReducer from "../features/books/booksReducer";
import categriesReducer from "../features/categories/categoriesReducer";
import authorsReducer from "../features/authors/authorsReducer";

const rootReducer = combineReducers({
    global: globalReducer,
    books: booksReducer,
    categories: categriesReducer,
    authors: authorsReducer
});

export default rootReducer;

现在我想使用图书精简器中的authors精简器中的某些状态,如何使用reduce-reducers包实现该状态?

1 个答案:

答案 0 :(得分:0)

reduce-reducers的作用类似于减速器的“合并”:

const reducer = (state = 0, action) => {
    switch (action.type) {
        case 'ADD':
            return state + action.value;
        case 'MULTIPLE':
            return state * action.value;
        default:
            return state;
    }
};

同样可以用reduce-reducers来写:

const addReducer = (state = 0, action) => {
    switch (action.type) {
        case 'ADD':
            return state + action.value;
        default:
            return state;
    }
};
const multipleReducer = (state = 0, action) => {
    switch (action.type) {
        case 'MULTIPLE':
            return state * action.value;
        default:
            return state;
    }
};

const reducer = reduceReducers(addReducer, multipleReducer, 0);

因此,在您的任务上,这意味着您应该重写authorsReducerbooksReducer,以便将整个状态作为第一个参数,而不仅仅是其自己的authors部分:

const before = (state = [], action) => {
    switch (action.type) {
        case `NEW_BOOK`:
            return state.concat([action.book]);
        default:
            return state;
    }
}

const now = (state = {}, action) => {
    switch (action.type) {
        case `NEW_BOOK`:
            return {
                ...state,
                books: state.books.concat([action.book]),
            };
        default:
            return state;
    }
}

但是!!我认为这不是您真正想要的。

还有另一个软件包可以完全满足您的需求combine-section-reducers

它允许您从任何其他reducer访问根状态:

const before = (state = [], action) => {
    switch (action.type) {
        case `NEW_BOOK`:
            return state.concat([action.book]);
        default:
            return state;
    }
}

const now = (state = [], action, rootState) => {
    switch (action.type) {
        case `NEW_BOOK`:
            return state.concat([{
                ...action.book,
                author: rootState.authors[action.book.authorId],
            }]);
        default:
            return state;
    }
}