【问题标题】:__react-router/v4__How to access history instance in BrowserRouter?__react-router/v4__如何在 BrowserRouter 中访问历史实例?
【发布时间】:2017-01-15 12:21:02
【问题描述】:

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

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

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

不管怎样,这个例子已经不行了。

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

【问题讨论】:

标签: redux react-router


【解决方案1】:

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

在即将到来的测试版中,您可以选择创建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')
  }
}

【讨论】:

    【解决方案2】:

    我暂时解决了这个我认为发生在 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();
    

    【讨论】:

      猜你喜欢
      • 2022-10-15
      • 2019-01-03
      • 2018-11-07
      • 2017-08-23
      • 2017-09-13
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 2018-06-29
      相关资源
      最近更新 更多