如何获取 react-router v4 的历史记录? [英] How to get history on react-router v4?

查看:49
本文介绍了如何获取 react-router v4 的历史记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在从 React-Router v3 迁移到 v4 时遇到了一些小问题.在 v3 中,我可以在任何地方执行此操作:

I having some little issue migrating from React-Router v3 to v4. in v3 I was able to do this anywhere:

import { browserHistory } from 'react-router';
browserHistory.push('/some/path');

如何在 v4 中实现这一点.

How do I achieve this in v4.

我知道当您在组件中时,我可以使用 hoc withRouter、反应上下文或事件路由器道具.但对我来说不是这样.

I know that I could use, the hoc withRouter, react context, or event router props when you are in a Component. but it is not the case for me.

我正在寻找 NavigatingOutsideOfComponents 在 v4 中

I am looking for the equivalence of NavigatingOutsideOfComponents in v4

推荐答案

你只需要一个模块来导出一个 history 对象.然后,您将在整个项目中导入该对象.

You just need to have a module that exports a history object. Then you would import that object throughout your project.

// history.js
import { createBrowserHistory } from 'history'

export default createBrowserHistory({
  /* pass a configuration object here if needed */
})

然后,您将使用 <Router> 组件,而不是使用内置路由器之一.

Then, instead of using one of the built-in routers, you would use the <Router> component.

// index.js
import { Router } from 'react-router-dom'
import history from './history'
import App from './App'

ReactDOM.render((
  <Router history={history}>
    <App />
  </Router>
), holder)

// some-other-file.js
import history from './history'
history.push('/go-here')

这篇关于如何获取 react-router v4 的历史记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆