反应路由器4 history.listen永不触发 [英] React router 4 history.listen never fires

查看:570
本文介绍了反应路由器4 history.listen永不触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

切换到路由器v4和历史记录v4.5.1,现在历史记录侦听器不起作用

Switched to router v4 and history v4.5.1 and now history listener not working

import createBrowserHistory from 'history/createBrowserHistory'
const history = createBrowserHistory()

history.listen((location, action) => {
  console.log(action, location.pathname, location.state)  //  <=== Never happens
})

render(
  <Provider store={store}>
    <Router history={history}>
      ...
    </Router>
  </Provider>,
  document.getElementById('root')
)

任何想法为什么忽略它?

Any ideas why it is being ignored?

推荐答案

由于您使用的是BrowserRouter(如问题注释中所述,带有导入别名Router,因此它并不在乎您传递的历史记录属性。而是使用 int最终创建新的浏览器历史记录并将其分配给路由器。因此,您监听并在Router中使用的历史实例是不同的。这就是您的听众无法正常工作的原因。

Since you are using BrowserRouter(with import alias Router as mentioned in comments of the question), it doesn't care the history prop you pass in. Instead of that it internally creates and assigns new browser history to the Router. So the history instance that you listen and being used in Router is not the same. That's why your listener doesn't work.

导入原始路由器。

import { Router } from 'react-router-dom';

它将按您的预期工作。

这篇关于反应路由器4 history.listen永不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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