在Redux文档提供的example之后,我设置了我的动作创建者:
export function createAlbumType(props) {
return function (dispatch, getState) {
dispatch({
type: CREATE_ALBUM_TYPE_REQUEST,
});
axios.post(`${ALBUM_TYPES_URL}`, props).then(
response => dispatch({
type: CREATE_ALBUM_TYPE_SUCCESS,
response,
}),
error => dispatch({
type: CREATE_ALBUM_TYPE_FAILURE,
error,
})
);
};
}
成功保存我的相册类型后,我想简单地将用户重定向回索引页面。不幸的是,我在发送后没有得到承诺。基于我的代码,似乎是什么问题?我使用redux-thunk
作为我的中间件,使用react-redux-router
作为路由。
onCreateSubmit(values) {
const { dispatch } = this.props;
return dispatch(createAlbumType(values))
.then((action) => {
if (action.type === 'CREATE_ALBUM_TYPE_SUCCESS') {
dispatch(push('/album_types'));
}
});
}
const store = createStore(reducers, {}, compose(
applyMiddleware(
routerMiddleware(browserHistory),
thunkMiddleware
),
window.devToolsExtension ? window.devToolsExtension() : f => f
)
);
const history = syncHistoryWithStore(browserHistory, store)
ReactDOM.render(
<Provider store={ store } >
<Router history={ history } routes={ routes } />
</Provider>,
document.getElementById('root')
);
答案 0 :(得分:1)
redux行动不会返回承诺。你应该返回axios.post函数。
export function createAlbumType(props) {
return function (dispatch, getState) {
dispatch({
type: CREATE_ALBUM_TYPE_REQUEST,
});
return axios.post(`${ALBUM_TYPES_URL}`, props).then(
response => dispatch({
type: CREATE_ALBUM_TYPE_SUCCESS,
response,
}),
error => dispatch({
type: CREATE_ALBUM_TYPE_FAILURE,
error,
})
);
};
}
答案 1 :(得分:0)
我建议不要这样做:
return dispatch(createAlbumType(values))
.then((action) => {
if (action.type === 'CREATE_ALBUM_TYPE_SUCCESS') {
dispatch(push('/album_types'));
}
});
}
您正在使用此if (action.type)
重新创建减速器。您应该在createAlbumType
内的.post().then()
行动中发货。这样一切都包含在应有的位置。