【发布时间】:2019-08-02 03:00:26
【问题描述】:
我不确定为什么我必须检查我的减速器中是否存在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 写得有点奇怪,所以我修复了它,但如果我删除 if statement,我仍然会收到错误 actions is undefined :'(
import {fetchRoles as fetchRolesAction} from '../../../actions/party-actions';
...
export const mapDispatchToProps = dispatch => ({
fetchRoles: () => dispatch(fetchRolesAction())
});
【问题讨论】:
-
代码对我来说看起来不错。你是如何在根减速器中注册减速器的?还包括 thunk 中间件吗?
-
@Clarity 刚刚添加了上面的商店代码
-
代码看起来没问题。为什么减速器中的双重导出?
-
奇怪,商店代码还可以。我可能会从 thunk 动作开始调试,并检查它是否/实际调度了哪种动作。
-
@Clarity 啊,测试就是这样写的!
标签: javascript reactjs redux async-await reducers