62

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

  • container挂钩到redux并处理操作、存储订阅等
  • list显示我的项目列表
  • new这是一种将新项目添加到列表中的表单

我有一些反应路由器路线如下:

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

以便显示 thelist或 theform但不能同时显示。

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

到目前为止,我的解决方案是.then()在 async 之后有一个dispatch

dispatch(actions.addProduct(product)
  .then(this.transitionTo('products'))
)

这是执行此操作的正确方法还是我应该以某种方式触发另一个动作来触发路线更改?

4

5 回答 5

29

如果您不想使用像Redux Router这样更完整的解决方案,您可以使用Redux History Transitions,它可以让您编写如下代码:

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 兼容。

于 2015-10-03T12:09:32.387 回答
26

我最终创建了一个超级简单的中间件,大致如下所示:

import history from "../routes/history";

export default store => next => action => {

    if ( ! action.redirect ) return next(action);

    history.replaceState(null, action.redirect);
}

所以从那里你只需要确保你的successful行为有一个redirect属性。另请注意,此中间件不会触发next(). 这是故意的,因为路线转换应该是动作链的末端。

于 2015-09-18T09:35:57.860 回答
19

对于那些使用中间件 API 层来抽象他们对isomorphic-fetch之类的使用的人,并且恰好也在使用redux-thunk,您可以简单地将dispatchPromise 链接到您的操作中,如下所示:

import { push } from 'react-router-redux';
const USER_ID = // imported from JWT;

function fetchUser(primaryKey, opts) {
    // this prepares object for the API middleware
}

// this can be called from your container
export function updateUser(payload, redirectUrl) {
    var opts = {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
    };
    return (dispatch) => {
        return dispatch(fetchUser(USER_ID, opts))
            .then((action) => {
                if (action.type === ActionTypes.USER_SUCCESS) {
                    dispatch(push(redirectUrl));
                }
            });
    };
}

这减少了将库添加到代码中的需要,如这里建议的那样,并且还可以很好地将您的操作与它们的重定向放在一起,就像在redux-history-transitions中所做的那样。

这是我的商店的样子:

import { createStore, applyMiddleware } from 'redux';
import rootReducer from '../reducers';
import thunk from 'redux-thunk';
import api from '../middleware/api';
import { routerMiddleware } from 'react-router-redux';

export default function configureStore(initialState, browserHistory) {
    const store = createStore(
        rootReducer,
        initialState,
        applyMiddleware(thunk, api, routerMiddleware(browserHistory))
    );

    return store;
}
于 2016-03-28T19:42:07.113 回答
0

我知道我在聚会上有点晚了,因为 react-navigation 已经包含在 react-native 文档中,但它仍然对在他们的应用程序中使用/使用 Navigator api 的用户有用。我尝试过的有点骇人听闻,一旦 renderScene 发生,我就会将导航器实例保存在对象中-

renderScene(route, navigator) {
      const Component = Routes[route.Name]
      api.updateNavigator(navigator); //will allow us to access navigator anywhere within the app
      return <Component route={route} navigator={navigator} data={route.data}/>

}

我的 api 文件是这样的

'use strict';

//this file includes all my global functions
import React, {Component} from 'react';
import {Linking, Alert, NetInfo, Platform} from 'react-native';
var api = {
    navigator,
    isAndroid(){
        return (Platform.OS === 'android');
    },
    updateNavigator(_navigator){
      if(_navigator)
          this.navigator = _navigator;
    },
}

module.exports = api;

现在在你的行动中你可以简单地打电话

api.navigator.push({Name:'routeName', data:WHATEVER_YOU_WANTED_TO_PASS)

您只需要从模块中导入您的 api。

于 2017-03-24T12:29:26.820 回答
0

如果您使用react-reduxreact-router,那么我认为这个链接提供了一个很好的解决方案。

这是我使用的步骤:

  • 通过在 react-routerhistory组件中渲染<Route/>组件或使用withRouter.
  • 接下来,创建您要重定向到的路线(我称为 mine to)。
  • history第三,用和调用你的 redux 操作to
  • 最后,当您想要重定向时(例如,当您的 redux 操作解析时),调用history.push(to).
于 2018-10-10T22:21:06.447 回答