在成功的异步 redux 操作上转换到另一条路线 [英] Transition to another route on successful async redux action

查看:21
本文介绍了在成功的异步 redux 操作上转换到另一条路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组非常简单的反应组件:

I have a pretty simple set of react components:

  • container 挂接到 redux 并处理操作、存储订阅等
  • list 显示我的物品列表
  • new 这是一种向列表中添加新项目的表单
  • container that hooks into redux and handles the actions, store subscriptions, etc
  • list which displays a list of my items
  • new which is a form to add a new item to the list

我有一些 react-router 路由如下:

I have some react-router routes as follows:

<Route name='products' path='products' handler={ProductsContainer}>
  <Route name='productNew' path='new' handler={ProductNew} />
  <DefaultRoute handler={ProductsList} />
</Route>

以便显示 listform,但不能同时显示两者.

so that either the list or the form are shown but not both.

我想要做的是在成功添加新项目后让应用程序重新路由回列表.

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.

到目前为止,我的解决方案是在异步 dispatch 之后使用 .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?

推荐答案

如果你不想使用像 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'
        }
      })
    }
  };
}

这类似于您的建议,但稍微复杂一些.它仍然使用相同的 history 库,因此它与 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆