问题描述
我是新来的反应者,现在我使用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,gamesList: action.payload
};
case gameActionTypes.FETCH_GAMES_FAILURE:
return{
...state,errorMessage: action.payload
};
default:
return {
state
};
}
};
和 rootReducer
export default combineReducers({
admin : adminReducer,game: gameReducer,})
我还添加了redux-logger以检查状态,这就是我在控制台中看到的内容
那么为什么我的游戏对象中有2个状态等级?并且与admin对象相同。在将redux-thunk添加到项目之前,我没有这个问题。在添加redux-thunk currentAdmin
之前是admin
的直接子代。但是现在之间有一个状态对象。
解决方法
default:
return {
state
};
应该是
default:
return state
现在,每当您按下default
时,state.whatever
就会变成state.state.whatever