首页 > 解决方案 > react redux-thunk 将状态包装在另一个状态中

问题描述

我是新手,现在我使用 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 来检查状态,这就是我在控制台中得到的 在此处输入图像描述

那么为什么我的游戏对象中有 2 级状态呢?管理对象也一样。在我将 redux-thunk 添加到项目之前,我没有这个问题。在添加 redux-thunk 之前currentAdminadmin. 但是现在之间有一个状态对象。

标签: javascriptreactjsreduxredux-thunk

解决方案


default:
        return {
            state
        };

应该只是

default:
        return state

现在任何时候你点击default,state.whatever正在变成state.state.whatever


推荐阅读