原来这么用是没有问题的,自从更新了create-react-app重新eject与更新了一些依赖库就出现了问题
1. store
export const history = createHashHistory({
basename: '',
hashType: 'slash',
});
const initialState = {};
const enhancers = [];
const middleware = [
thunk,
routerMiddleware(history),
];
if (process.env.NODE_ENV === 'development') {
const devToolsExtension = window.devToolsExtension;
if (typeof devToolsExtension === 'function') {
enhancers.push(devToolsExtension());
}
}
const composedEnhancers = compose(
applyMiddleware(...middleware),
...enhancers,
);
const store = createStore(
rootReducer,
initialState,
composedEnhancers,
);
export default store;
2. action
export const FETCH_EXPORT_STAGE = 'FETCH_EXPORT_STAGE'
const makeActionCreator = (type, ...argNames) => (...args) => {
const action = { type };
argNames.forEach((arg, index) => {
action[argNames[index]] = args[index];
});
return action;
};
export const pushExportStage = makeActionCreator(FETCH_EXPORT_STAGE, 'payload')
export const fetchExportStage = () => async (dispatch) => {
const stages = await fetch('/api/findSchoolType')
dispatch(pushExportStage(stages))
return stages
}
3.component
componentDidMount () {
this.props.fetchExportStage()
.then(stages => {
if (!stages.length) return
const defaultStageId = stages[0].id
this.props.fetchExportSchoolByStage(defaultStageId).then(schools => {
this.setState({schools})
})
this.props.fetchExportIndicatorByStage(defaultStageId).then(indicators => {
this.setState({indicators})
})
});
}
报错信息
×
Unhandled Rejection (Error): Actions must be plain objects. Use custom middleware for async actions.
▶ 6 stack frames were collapsed.
(anonymous function)
src/routes/home/components/index.js:48
45 | .then(stages => {
46 | if (!stages.length) return
47 | const defaultStageId = stages[0].id
> 48 | this.props.fetchExportSchoolByStage(defaultStageId).then(schools => {
49 | ^ this.setState({schools})
50 | })
51 | this.props.fetchExportIndicatorByStage(defaultStageId).then(indicators => {
package.json
"react": "^16.5.2",
"react-redux": "^5.0.7",
"react-redux-loading-bar": "^4.0.8",
"react-router-dom": "^4.3.1",
"react-router-redux": "^5.0.0-alpha.9",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0",
fetchExportSchoolByStage 不应该返回一个promise对象,而是返回一个函数(少写了一次箭头