我的反应很新,所以这可能是一个愚蠢的问题。
我正在开发一个用于管理rss feed的应用程序,所以我整个应用程序的结构都与此类似
<div className="App">
<Header />
<Feeds />
</div>
两个组件都有自己的减速器和动作。
当我尝试从标头组件创建新的供稿(实际上是在供稿还原器中进行管理)时,出现了问题。所以我必须从headerReducer中访问feedsReducer的状态。
目前我不确定如何继续。
我应该从标题组件访问feed减速器吗? (这也意味着feedsReducer需要知道我的标头操作)
我将添加一些代码以使问题清楚
index.js
import feedsReducer from './components/Feeds/FeedsReducer';
import headerReducer from './components/Header/HeaderReducer';
const rootReducer = {
feeds:feedsReducer,
header: headerReducer
};
const store = createStore(combineReducers(rootReducer));
Header / Header.js
import { ADD_FEED } from './actions';
class Header extends Component {
state = {
feedUrl: ""
};
addFeed = () => {
axios.post(
'/feeds/add',
{
url: 'myNewRssFeed.com'
})
.then(feed => {
//this is calling the HeaderReducer
this.props.addFeed(feed.data);
})
.catch(err => console.log(err));
}
}
const mapDispatchToProps = dispatch => {
return {
addFeed: (feed) => dispatch({ type: ADD_FEED, payload: { feed } })
};
};
export default connect(null, mapDispatchToProps)(Header);
Header / actions.js
export const ADD_FEED = "ADD_FEED";
HeaderComponent / HeaderReducer.js
const reducer = (state, action) => {
const newState = {
...state
}
switch (action.type) {
case storeActions.ADD_FEED:
// at this point newState.feeds doesn't exist because it's part from the FeedsReducer
newState.feeds = newState.feeds.push(action.payload.feed);
break;
}
return newState;
}
Feeds / FeedsReducer.js
const initialState = {
feeds: []
}
const reducer = (state = initialState, action) => {
const newState = {
...state
}
switch (action.type) {
//this action is commented because was recently moved to the headerComponent/actions.js
/* case storeActions.ADD_FEED:
newState.feeds = newState.feeds.push(action.payload.feed);
break; */
case storeActions.LOAD_FEEDS:
newState.feeds = action.payload.feeds;
break;
}
return newState;
}
感谢您的咨询。
答案 0 :(得分:0)
我真的不认为您需要以任何方式访问reducer。 Reducer函数将根据其监听的动作来更新商店。 这是一个示例:
import * as constants from 'constantpathhere';
export function feedReducer(state = INITIAL_STATE, action) {
const { type, payload } = action;
switch(type) {
case constants.ADD_FEED: // listen to ADD_FEED action
return {... state, data: payload };
case constants.LOAD_FEEDS: // listen to LOAD_FEEDS
return {...state, loading: true }
...
default:
return state;
}
}
export function headReducer(state = INITIAL_STATE, action) {
const { type, payload } = action;
switch(type) {
case constants.ANY_ACTION: // listen to ADD_FEED action
return {... state, data: payload };
case constants.ANY_OTHER_ACTION_LOADING: // listen to LOAD_FEEDS
return {...state, loading: true }
...
default:
return state;
}
}
//ACTIONS
export function loadFeeds() {
return {
type: constants.LOAD_FEEDS
}
}
export function addFeed(payload) {
return {
type: constants.ADD_FEED,
payload
}
}
export function triggerAnyAction(payload) {
return {
type: constants.ANY_ACTION,
payload
}
}
上面的这些动作可以从任何组件中分发,无论是Header
还是Feeds
,只有侦听该特定动作的减速器才能更新商店。
简而言之,您只需要知道将哪个动作分派到哪里,并且只有减速器列出该动作就可以执行您指示的动作