【问题标题】:redux-observable perform transition once the action fires一旦动作触发,redux-observable 执行转换
【发布时间】:2017-10-05 07:41:54
【问题描述】:

我将 redux-observable 与史诗一起使用。

 return action$.ofType('APPLY_SHOPPING_LISTS')
            .flatMap(() => Observable.concat(Observable.of({ type: 'APPLYING_SHOPPING_LISTS' }), Observable.of({ type: 'APPLIED_SHOPPING_LISTS' }).delay(5000);

史诗完成触发“APPLIED_SHOPPING_LISTS”后,我想执行转换,我正在使用 react-router。这样做的最佳地点是什么?我看到了 redux-history-transitions,这是我应该使用的插件吗?

此外,我确实使用了 redux-history-transitions 并将其更改为以下内容

return action$.ofType('APPLY_SHOPPING_LISTS')
            .flatMap(() => Observable.concat(Observable.of({ type: 'APPLYING_SHOPPING_LISTS' }), Observable.of({ type: 'APPLIED_SHOPPING_LISTS', meta: {
                        transition: (prevState, nextState, action) => ({
                            pathname: '/Shopping',
                        }),
                    } }).delay(5000);

这似乎确实改变了 url 并发生了转换,但是我在“/Shopping”路径下配置的组件不会呈现。它只是停留在当前页面上。这就是我的路线的样子

<Route path='/' component={App}>
    <IndexRoute component={LoginContainer} />
    <Route path='login' component={LoginContainer} />
    <Route path='landing' component={LandingComponent} />
    <Route path='Shopping' component={ShoppingPathComponent} />
</Route>

【问题讨论】:

    标签: react-router redux-observable


    【解决方案1】:

    如果您使用 react-router v3 或更早版本,则可以使用中间件,该中间件可让您使用 redux 操作推送/替换历史记录,例如 react-router-redux。我不熟悉 redux-history-transitions,但它可能(或可能不会)类似地工作。

    使用 react-router-redux,它只是意味着在您希望它发生时发出您想要转换历史的操作。

    因此,您需要导入 push 动作创建者,并将其作为另一个动作添加到 APPLIED_SHOPPING_LISTS 之后:

    Observable.of(
      { type: 'APPLIED_SHOPPING_LISTS' },
      push('/Shopping')
    )
    

    总之是这样的:

    import { push } from 'react-router-redux';
    
    const somethingEpic = action$ =>
      action$.ofType('APPLY_SHOPPING_LISTS')
        .flatMap(() => Observable.concat(
          Observable.of({ type: 'APPLYING_SHOPPING_LISTS' }),
          Observable.of(
            { type: 'APPLIED_SHOPPING_LISTS' },
            push('/Shopping')
          )
            .delay(5000)
        ));
    

    如果您使用的是 v4,在撰写本文时 react-router-redux 尚不兼容,但它处于活动状态 development here

    【讨论】:

    • 但这不意味着我正在做一个动作的副作用吗?如果我使用推送?
    • @tmpdev 你能改写这个问题吗?
    • 根据redux (flux) 的动作不应该避免副作用吗?
    • 动作本身只是普通的旧 javascript 对象。它们本身什么也不做,而是基本上是表明意图的事件。在 redux-observable 的情况下,您将侦听的动作表示执行某些副作用的意图,例如“Do X please”。你的史诗会监听那个意图,然后它自己(史诗)执行实际的副作用,然后选择性地发出其他动作来显示其他意图,例如“X 完成”。
    猜你喜欢
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 2019-03-01
    • 1970-01-01
    • 2018-03-09
    • 2016-10-02
    相关资源
    最近更新 更多