如果你想用这种方式听路线的变化,我想你应该用
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')
)
这是我得到的控制台日志:
希望有帮助。