__react-router / v4__如何访问BrowserRouter中的历史记录实例?

时间:2017-01-15 12:21:02

标签: redux react-router

我想写一个redux-middleware来处理react-router v4应用程序中的历史pushState。

问题是我无法轻松访问BrowserRouter中正确的history实例,因为它是在BrowserRouter中通过createHistory创建的。

我的问题:是否有一种简单的方法可以将history单例传递给BrowserRouter组件?

无论如何,这个例子不再适用了。

https://github.com/ReactTraining/react-router/blob/7f6706dab4827afc1c26a58418f8ef8c8ab40125/website/examples/Redux.js

2 个答案:

答案 0 :(得分:0)

在当前的alpha版本中,没有良好的方法来执行此操作。有一些解决方法涉及创建自己的<___Router>组件或通过history变量访问context.router方法(并将其传递给您的操作以便中间件可以使用)。 / p>

在即将推出的测试版中,您可以选择创建history个实例并将其传递给<Router>,这样您就可以在组件外部进行导航。

// history.js
import { createHistory } from 'history'
export default createHistory()

// index.js
import history from './history'
render((
  <Router history={history}>
    <App />
  </Router>
), holder)

// middleware.js
import history from './history'
export default store => dispatch => action => {
  if (action.type === 'ROUTING_ACTION') {
    history.push('/new_location')
  }
}

答案 1 :(得分:0)

我暂时解决了这个问题,我认为这个问题发生在react-router v4。(我也有react-router-dom),如下所示:

将历史对象从组件(选择器)作为参数传递给动作创建者,然后在动作创建者定义中调用history.push('/ new-route')

export function register(user, history) { 
// this history is the argument from the register call in the component
    return function (dispatch) {
         dispatch(initRequest()); // show spinner or something
         return Auth.register(user)
             .then(()=> {
                dispatch(registerSuccess());
                history.push('/new-route');

        }).catch((err)=> dispatch(setErrorMessage()))
    }
}

我还必须指出createHistory对我不起作用,我不得不这样做:

import createBrowserHistory from 'history/createBrowserHistory'
const history = createBrowserHistory();