[英]change state in another reducer
i started to study the react.我开始研究反应。 here is my problem.
这是我的问题。 I have some reducers
我有一些减速器
let reducers = combineReducers({
user: userReducer,
index_page: indexReducer,
notifications: notificationsReducer
});
Notifications Reducer has its own state of notifications for their renderingand in indexReducer there is. Notifications Reducer 有自己的 state 通知用于它们的渲染,并且在indexReducer中有。 An axios request which, after the response, should draw a notification to the user - change state in notificationsReducer .
一个 axios 请求,在响应之后,应该向用户发出通知 - 在notificationsReducer中更改 state 。
I do not quite understand how to do this.我不太明白如何做到这一点。
This is my code:这是我的代码:
notificationsReducer通知减速器
let initialState = [
{id: 3, text: 'test_msg', state: 'error'}
];
export const createNotificationActionCreator = (msg_text, msg_state) => {
return {
type: 'SHOW_NOTIFY',
msg_text: msg_text,
msg_state: msg_state
}
}
const notificationsReducer = (state = initialState, action) => {
switch (action.type) {
case SHOW_NOTIFY:
let msg = {
text: action.msg_text,
msg_state: action.msg_state
};
state.push(msg);
break;
}
return state;
}
indexReducer索引减速器
const indexReducer = (state = initialState, action) => {
switch (action.type) {
case CREATE_NEW_BET:
let bet_data = new Object();
bet_data.bet = state.betAmount;
bet_data.color = action.color;
axios.get('http://localhost/createbet', {
params: {
bet_data
}
}).then(function (response) {
// CHANGE STATE IN notificationsReducer
});
break;
}
return state;
}
To update state in another reducer, I would suggest dispatching the SHOW_NOTIFY
action right after dispatching the CREATE_NEW_BET
.要在另一个 reducer 中更新 state,我建议在调度
CREATE_NEW_BET
之后立即调度SHOW_NOTIFY
操作。 This can be done using Redux Thunks .这可以使用Redux Thunks来完成。
Also read this Stack Overflow answer on suggestions to update state managed by another reducer: Updating state managed by another reducer另请阅读有关更新由另一个减速器管理的 state 的建议的堆栈溢出答案: 更新由另一个减速器管理的 state
With redux-thunk setup, this is what your thunk would look like:使用 redux-thunk 设置,这就是您的 thunk 的样子:
const createBetAndNotify = () => (dispatch) => {
return dispatch({ type: "CREATE_NEW_BET" }).then(() => {
dispatch({ type: "SHOW_NOTIFY" })
})
}
Then inside your React component, you would dispatch the above thunk:然后在你的 React 组件中,你会发送上面的 thunk:
dispatch(createBetAndNotify());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.