我正在开发一个普通的React JS应用程序并使用BrowserRouter。我需要知道路线何时发生变化,我发现的唯一事情就是使用同一个人的history package(反应训练)。
他们的例子看起来很容易但对我来说根本不起作用:
import createHistory from 'history/createBrowserHistory'
const history = createHistory()
console.log('a')
history.listen((location, action) => {
console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
console.log(`The last navigation action was ${action}`)
})
const A = props => <div>A <NavLink to="/b">b</NavLink></div>
const B = props => <div>B <NavLink to="/a">a</NavLink></div>
ReactDOM.render(
<BrowserRouter>
<div>
<Route path="/a" component={A}/>
<Route path="/b" component={B}/>
</div>
</BrowserRouter>,
document.getElementById('app')
)
控制台打印“a”但是当我点击并且我的网址发生变化时,调用回调永远不会被调用。
他们的文档中没有更多内容,所以有人知道缺少什么吗?
答案 0 :(得分:4)
如果您想以这种方式收听路线更改,我认为您应该使用Router
而不是BrowserRouter
,并将新创建的history
作为道具。
以下是包含更改的代码:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory'
const history = createHistory()
history.listen((location, action) => {
console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
console.log(`The last navigation action was ${action}`)
})
const A = props => <div>A <Link to="/b">b</Link></div>
const B = props => <div>B <Link to="/a">a</Link></div>
ReactDOM.render(
<Router history={history}>
<div>
<div>Hello!</div>
<Route path="/a" component={A}/>
<Route path="/b" component={B}/>
</div>
</Router>,
document.getElementById('root')
)
这是我得到的控制台日志:
希望它有所帮助。