如何在<Route/>之外访问历史对象在 React Router v4 中 [英] How to access history object outside <Route /> in React Router v4

查看:23
本文介绍了如何在<Route/>之外访问历史对象在 React Router v4 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

import {BrowserRouter 作为路由器,路线,关联来自'反应路由器-dom'const 路由 = () =>(<Router basename="/blog"><div><标题/><路由精确路径="/" component={Main}/><Route path="/article/:id" component={ArticleView}/>

</路由器>)

我可以通过 Main 和 ArticleView 组件中的 props 访问历史记录或匹配.但是我无法在

中访问它.有没有办法获取Header组件中的history对象?

解决方案

您可以使用 withRouter HOC 用于此.

在定义您的 Header 组件的地方,将导出包装在如下所示的 withRouter 调用中将使您的 Header 组件访问匹配、位置和历史

import {withRouter} from 'react-router'类头扩展组件{静态 propTypes = {匹配:PropTypes.object.isRequired,位置:PropTypes.object.isRequired,历史:PropTypes.object.isRequired}使成为 () {const { 匹配,位置,历史} = this.props返回<h2>标题</h2>}}导出默认 withRouter(Header)

I have this following code:

import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom'


const Routes = () => (
  <Router basename="/blog">
    <div>
      <Header />
      <Route exact path="/" component={Main}/>
      <Route path="/article/:id" component={ArticleView}/>
    </div>
  </Router>
)

I can access history or match via props in the Main and ArticleView component. But I cannot access it in the <Header />. Is there a way to get the history object in the Header component?

解决方案

You can use the withRouter HOC for this.

Where your Header component is defined, wrapping the export in a withRouter invocation like below will give your Header component access to match, location, and history

import {withRouter} from 'react-router'

class Header extends Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }
  render () {
    const { match, location, history } = this.props

    return <h2>The Header</h2>
  }
}

export default withRouter(Header)

这篇关于如何在&lt;Route/&gt;之外访问历史对象在 React Router v4 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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