gpt4 book ai didi

javascript - 如何将 reduce-reducers 与 combineReducers 一起使用

转载 作者:行者123 更新时间:2023-12-04 15:53:20 25 4
gpt4 key购买 nike

所以,我试图在另一个 reducer 中使用一个 reducer 的一些状态,我寻找了一个解决方案,似乎 reduce-reducers 包确实做到了这一点,但这是我的问题...

我有以下 rootReducer.js 文件,我在其中导入所有 reducer 并将它们与 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;

现在我想在 books reducer 中使用来自 authors reducer 的一些状态,如何使用 reduce-reducers 包实现?

最佳答案

reduce-reducers 的工作方式类似于 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;
}
}

关于javascript - 如何将 reduce-reducers 与 combineReducers 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52967554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com