React router 4 history.listen 永远不会触发 [英] React router 4 history.listen never fires

查看:24
本文介绍了React router 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),它并不关心您传入的历史道具.而不是它内部为路由器创建和分配新的浏览器历史.所以你监听的和在 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';

它会按您的预期工作.

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

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