为什么redux存储只获取上次调度操作的值



我正在redu:的动作阶段尝试进行多调度动作

这是我的代码:

export const get_data_time_slot_week = (params) => {
return async (dispatch) => {
dispatch({
type: common.CALL_API_REQUEST,
});
const res = await callAPI.post(TIME_SLOT_WEEK + GET, {
params: { ...params },
});
if (res.status === 200 && res.data.code >= 0) {
//Here, I get new state of Selector timeSlotWeek
dispatch({
type: timeSlotWeek.GET_DATA_TIME_SLOT_WEEK_SUCCESS,
payload: {
data: [...res.data.data],
dataPage: { ...res.data.dataPage },
errCode: res.data.code,
},
});
//And here, I lost state of a Selector timeSlotWeek add get new state of Selector common
dispatch({
type: common.GET_FEEDBACK,
payload: {
msg: "__msg_can_not_to_server",
},
});
}
};

};

为什么会发生这种事?我如何在代码中保持timeSlotWeek的状态和相同的流?

这是我通过Redux工具检查时的结果

GET_DATA_TIME_SLOT_WEEK_SUCCESS     =>    data: { 0: {...}, 1{...} }
GET_FEEDBACK                        =>    data: {}
msg: "new msg"

这是我的商店.js

import { createStore, applyMiddleware } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import rootReducer from "./reducers";
import thunk from "redux-thunk";
const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(thunk)));
export default store;

这是我的

import { combineReducers } from "redux";
import feedback from "./feedback.reducer";
import loadingReducer from "./loading.reducer";
import timeSlotWeek from "./timeSlotWeek.reducer";
const rootReducer = combineReducers({
dataTimeSlotWeek: timeSlotWeek,
loading: loadingReducer,
feedback: feedback,
});
export default rootReducer;

感谢您的帮助

更新:问题解决:因为在我的reducer of timeSlotWeek.reducer中,我有一个默认情况,当我调度另一个操作时,这个情况将运行,并使timeSlotWeek的状态变为initState。

import { common, timeSlotWeek } from "../actions/constants";
const initState = {
data: [],
};
export default (state = initState, action) => {
switch (action.type) {
case timeSlotWeek.GET_DATA_TIME_SLOT_WEEK_SUCCESS:
state = {
// Pass payload to this
};
break;
default:
state = { ...initState };
}
return state;
};

我通过这种方式修复它:

import { common, timeSlotWeek } from "../actions/constants";
const initState = {
data: [],
};
export default (state = initState, action) => {
switch (action.type) {
case timeSlotWeek.GET_DATA_TIME_SLOT_WEEK_SUCCESS:
state = {
// Pass payload to this
};
break;
**case common.CALL_API_FINISH:
state = state;
break;
case common.GET_FEEDBACK:
state = state;
break;**
default:
state = { ...initState };
}
return state;
};

有比我更好的方法吗?感谢cmt

默认的reducer case应该始终返回当前状态对象。我想不出任何其他的反例(尽管我看到一些教程在这里抛出了一个错误,但你通常不想这样做,因为它增加了不必要的错误处理,并使一切变得复杂(。

您只需要为状态切片缩减器需要处理的操作定义事例,否则,让默认事例通过返回当前状态来处理它。

const initState = {
data: [],
};
export default (state = initState, action) => {
switch (action.type) {
case timeSlotWeek.GET_DATA_TIME_SLOT_WEEK_SUCCESS:
return {
// Pass payload to this
};
default:
return state;
}
};

如果您需要重置某些状态,则使用另一个操作和情况,即:

case 'resetTimeSlotWeek':
return initState;

相关内容

  • 没有找到相关文章

最新更新