作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以,我试图在另一个 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);
所以在你的任务中,这意味着你应该重写你的 authorsReducer
和 booksReducer
以便它获得整个状态作为第一个参数,而不仅仅是它自己的 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/
我是一名优秀的程序员,十分优秀!