成功执行异步redux操作后转换到另一个路由 [英] Transition to another route on successful async redux action
问题描述
我有一套非常简单的反应组件:
I have a pretty simple set of react components:
-
container
that挂钩到 redux 并处理行动,存储订阅等。 -
list
显示我的项目列表 -
new
这是一个用于向列表中添加新项目的表单
container
that hooks into redux and handles the actions, store subscriptions, etclist
which displays a list of my itemsnew
which is a form to add a new item to the list
我有一些 react-router 路由如下:
<Route name='products' path='products' handler={ProductsContainer}>
<Route name='productNew' path='new' handler={ProductNew} />
<DefaultRoute handler={ProductsList} />
</Route>
以便列表
或<显示code>表单但不是两者。
我想做的是让应用程序重新路由回来一旦成功添加新项目,就到列表中。
What I'd like to do is to have the application re-route back to the list once a new item has been successfully added.
到目前为止,我的解决方案是在异步发送后有一个
: .then()
My solution so far is to have a .then()
after the async dispatch
:
dispatch(actions.addProduct(product)
.then(this.transitionTo('products'))
)
这是正确的方法吗?我以某种方式触发另一个动作来触发路线改变?
Is this the correct way to do this or should I fire another action somehow to trigger the route change?
推荐答案
如果您不想使用更完整的解决方案,例如< a href =https://github.com/acdlite/redux-react-router =noreferrer> Redux Router ,您可以使用 Redux History Transitions ,它允许你编写如下代码:
If you don't want to use a more complete solution like Redux Router, you can use Redux History Transitions which lets you write code like this:
export function login() {
return {
type: LOGGED_IN,
payload: {
userId: 123
}
meta: {
transition: (state, action) => ({
path: `/logged-in/${action.payload.userId}`,
query: {
some: 'queryParam'
},
state: {
some: 'state'
}
})
}
};
}
这类似于你的建议但更复杂一点。它仍然使用相同的历史库,因此它与React Router兼容。
This is similar to what you suggested but a tiny bit more sophisticated. It still uses the same history library under the hood so it's compatible with React Router.
这篇关于成功执行异步redux操作后转换到另一个路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!