Action.type Redux Reducer 中的未定义错误

Action.type undefined error in Redux Reducer

我不确定为什么我必须检查 actions 是否存在于我的减速器中。难道是因为我们在我们的动作中使用了 async await / API 方法?

减速机

export const partyReducer = (state = initState, action) => {
    if (action) { // <-- should not need this
        switch (action.type) {
            case Actions.SET_ROLES: {
                const roles = formatRoles(action.roles);

                return {
                    ...state,
                    roles
                };
            }

            default:
                return state;
        }
    }
    return state;
};

export default partyReducer;

操作

import {getRoles} from '../shared/services/api';

export const Actions = {
    SET_ROLES: 'SET_ROLES'
};

export const fetchRoles = () => async dispatch => {
    try {
        const response = await getRoles();
        const roles = response.data;

        dispatch({
            type: Actions.SET_ROLES,
            roles
        });
    } catch (error) {
        dispatch({
            type: Actions.SET_ROLES,
            roles: []
        });
    }
};

调度动作的组件:

componentDidMount() {
        this.props.fetchRoles();
        this.onSubmit = this.onSubmit.bind(this);
}

...

export const mapDispatchToProps = dispatch => {
    return {
        fetchRoles: () => {
            dispatch(fetchRoles());
        }
    };
};

商店

import {createStore, combineReducers, applyMiddleware, compose} from 'redux';
import thunk from 'redux-thunk';
import {reducer as formReducer} from 'redux-form';

// Reducers
import partyReducer from '../reducers/party-reducer';

export default function configureStore(initialState) {
    let reducer = combineReducers({
        form: formReducer,
        party: partyReducer
    });

    let enhancements = [applyMiddleware(thunk)];

    if (process.env.PROD_ENV !== 'production' && typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION__) {
        enhancements.push(window.__REDUX_DEVTOOLS_EXTENSION__());
    }

    return createStore(reducer, initialState, compose(...enhancements));
}

我试过的

我注意到我的 mapDispatchToProps 写得有点奇怪所以我修复了它,但是如果我删除 if statement 我仍然会收到错误 actions is undefined :'(

import {fetchRoles as fetchRolesAction} from '../../../actions/party-actions';

...

export const mapDispatchToProps = dispatch => ({
    fetchRoles: () => dispatch(fetchRolesAction())
});

想通了!是我的考验!

it('returns expected initState', () => {
    let expected = {roles: []};
    let actual = partyReducer();

    expect(actual).toEqual(expected);
});

^ 上面的测试假设如果没有传入状态,则初始状态是否为 return。但是应始终传入操作。

修复:

it('returns expected initState', () => {
     let expected = {roles: []};
     let actual = partyReducer(undefined, {}); // <-- undefined state, + action

     expect(actual).toEqual(expected);
});