要在一系列其他操作完成并保存到商店时启动页面更改,请发送以下redux-thunk。这里的关键是你有一个返回承诺的 thunk 链,然后一旦它们都完成,你可以用另一个动作更新路由器。
在组件中:
import React from 'react';
import { push } from 'react-router-redux';
import { connect } from 'react-redux';
import { doStuff, doMoreStuff } from './actions';
class SomeComponent extends React.Component {
...
onClick = e => {
const { doStuff, doMoreStuff, push } = this.props; // these are already wrapped by dispatch because we use connect
...
doStuff()
.then(r => doMoreStuff())
.then(r => push('/newPath')) // if actions succeeded, change route
.catch(e => console.warn('doStuff() or doMoreStuff failed'));
...
}
...
}
export default connect(null, { doStuff, doMoreStuff, push })(SomeComponent);
./actions.js中的一些操作:
export function doStuff() {
return (dispatch, getState) => {
return API.getSomeInfo()
.then(info => dispatch({ type: 'GET_SOME_INFO', payload: info }))
}
}
export function doMoreStuff() {
return (dispatch, getState) => {
return API.getSomeMoreInfo()
.then(info => dispatch({ type: 'GET_SOME_MORE_INFO', payload: info }));
}
}
或者,您可以做出如下所示的单个承诺,重定向发生的地方:
export function doAllStuff() {
return dispatch => {
return Promise.all(doStuff(), doAllStuff())
.then(results => dispatch(push('/newPath')))
.catch(e => console.warn('Not all actions were successful'))
}
}
启动它的组件代码就是
onClick = e => {
...
doAllStuff(); // Since we caught the promise in the thunk, this will always resolve
...
}