【发布时间】:2020-08-11 17:33:50
【问题描述】:
我是新手,现在我使用 redux 和 redux-thunk 创建了一个简单的应用程序,它异步调用 API。这是我的游戏gameAction:
export const fetchGamesStartAsync = () => {
return dispatch => {
dispatch(fetchGamesStart());
axiosGenCfg.post('/game/get',{
"page" : 1,
"size" : 10
})
.then(({ res }) => {
dispatch(fetchGamesSuccess(res));
})
.catch(err => {
dispatch(fetchGamesFailure(err.message));
});
}
};
const fetchGamesStart = () => ({
type: gameActionTypes.FETCH_GAMES_START,
});
const fetchGamesFailure = () => ({
type: gameActionTypes.FETCH_GAMES_FAILURE,
});
const fetchGamesSuccess = (games) => ({
type: gameActionTypes.FETCH_GAMES_SUCCESS,
payload:{
...games
}
});
这是我的 gameReducer:
const INITIAL_STATE= {
gamesList : null,
isFetching: false,
errorMessage : undefined
};
const gameReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case gameActionTypes.FETCH_GAMES_START:
return{
...state,
isFetching: true
};
case gameActionTypes.FETCH_GAMES_SUCCESS:
return{
...state,
isFetching: false,
gamesList: action.payload
};
case gameActionTypes.FETCH_GAMES_FAILURE:
return{
...state,
isFetching: false,
errorMessage: action.payload
};
default:
return {
state
};
}
};
在rootReducer
中export default combineReducers({
admin : adminReducer,
game: gameReducer,
})
我还添加了 redux-logger 来检查状态,这就是我在 console 中得到的
那么为什么我的游戏对象中有 2 个状态级别?管理对象也一样。在我将 redux-thunk 添加到项目之前,我没有这个问题。在添加 redux-thunk 之前,currentAdmin 是 admin 的直接子代。但是现在之间有一个状态对象。
【问题讨论】:
标签: javascript reactjs redux redux-thunk