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

时间:2019-08-01 16:33:17

标签: javascript reactjs redux async-await reducers

我不确定为什么我的精简版中是否存在actions是否被迫进行检查。可能是因为我们在动作/ API方法中使用了async await吗?

减速器

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写的有点奇怪,所以我解决了这个问题,但是如果我删除actions is undefined,仍然会收到错误if statement:'(

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

...

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

1 个答案:

答案 0 :(得分:1)

想通了!是我的考试!

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

    expect(actual).toEqual(expected);
});
上面的

^测试旨在查看如果没有传递任何状态,则是否返回初始状态。但是应该始终传递操作。

修复:

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

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