如何在使用 react-router 成功异步调用后重定向?

How to redirect after successful Async call with react-router?

我正在使用 react-router 浏览我的 react/flux 应用程序。

Where I still have problems is: How is the best way to redirect to a new page (or just change the URI params) after a successful API call?

我有一个 API.js,我的异步调用在其中(使用超级代理)。实际调用是在我的应用程序中完成的-actions.js:

createWorkspace( workspace ) {
    Api.createWorkspace( workspace )
      .then(function( workspace ) {
        dispatch({ actionType: AppConstants.CREATE_WORKSPACE, workspace });
        history.replaceState('/workspace/' + workspace.body.data._id);
      }, function(error) {
        dispatch({ actionType: AppConstants.FAILED_TO_CREATE, error });
      });
  }

我正在调度成功或失败事件。所以一切都是根据通量模式。

如您所见,我正在使用 history.replaceState 来更改 URL。但它正在取代所有的东西,包括哈希。

老实说,这是一场噩梦。我发现 ES5 有反应 0.13 的东西,我发现 ES6 有反应路由器 0.14 和 ES6 有反应路由器 1.0 解决方案。

我什至不记得我是在哪里找到这个history.replace方法的。

我在用什么

有人可以告诉我我的问题出在哪里吗?为什么最直接的 ToDo,重定向,如此重要? 我应该只在这里使用普通 JavaScript 并自己操作浏览器 url 吗?

我花了一段时间才弄清楚最佳实践是什么。这就是我的做法。

创建一个history.js文件

import createBrowserHistory from 'history/lib/createBrowserHistory'

export default createBrowserHistory();

然后,不太好的解决方案,我必须替换整个 URL,所以我必须在创建新的时处理井号:

history.replaceState(null, '#/workspace/' + workspace.body.data._id);

这是我的 AppActions.js:

import AppConstants from '../constants/app-constants';
import { dispatch, register } from '../dispatchers/app-dispatcher';
import Api from '../lib/api';
import history from '../lib/history'

export default {
  addRestaurant ( restaurant ) {
    dispatch({ actionType: AppConstants.ADD_RESTAURANT, restaurant });
  },
  removeRestaurant ( restaurant ) {
    dispatch({ actionType: AppConstants.REMOVE_RESTAURANT, restaurant });
  },
  createWorkspace( workspace ) {
    Api.createWorkspace( workspace )
      .then(function( workspace ) {
        dispatch({ actionType: AppConstants.CREATE_WORKSPACE, workspace });
        history.replaceState(null, '#/workspace/' + workspace.body.data._id);
      }, function(error) {
        dispatch({ actionType: AppConstants.FAILED_TO_CREATE, error });
      });
  }
}

Working solution is here.