Mic*_* H. 2 reactjs react-router react-router-v4
我正在开发一个普通的React JS应用程序并使用BrowserRouter。我需要知道路线何时更改,而我发现的唯一内容是使用同一个人的历史记录包(反应训练)。
他们的例子看起来很简单,但对我来说根本不起作用:
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')
)
Run Code Online (Sandbox Code Playgroud)
控制台显示“ a”,但单击并更改URL时,永远不会调用监听回调。
他们的文档中没有更多内容,所以有人知道缺少什么吗?
如果你要听这样路线的变化,我认为你应该使用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')
)
Run Code Online (Sandbox Code Playgroud)
这是我得到的控制台日志:
希望能帮助到你。
| 归档时间: |
|
| 查看次数: |
1271 次 |
| 最近记录: |