我将React.js与Redux、React-Router和React-Router-Redux一起使用。
当商店达到特定状态时,我希望手动重新路由(或调用操作)。如果商店有一个特定的状态,我如何监听?我在哪里重路由或调用操作?
发布于 2016-01-30 06:28:52
如果这些调用是异步进行的,那么使用异步操作创建器和promise可以很好地处理这一问题。
// Action creator
function doTheStuff(someData, router) {
return dispatch => {
dispatch(somePendingAction());
return myRequestLib.post('/the-endpoint/', someData)
.then((response) => {
if (response.isTransactionDone) {
dispatch(transactionDoneAction(response));
router.transitionTo('/theUrl');
}
});
}
}我不会把它放到商店里,因为我相信商店唯一的工作就是包含/处理数据。
发布于 2016-01-30 07:35:10
若要在一系列其他操作已完成并持久化到存储区时启动页面更改,请调度以下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
...
}https://stackoverflow.com/questions/35093467
复制相似问题