简体   繁体   English

在 react-router-dom v5 中使用 BrowserRouter 未定义路由器上下文

[英]Router context undefined with BrowserRouter in react-router-dom v5

Have an issue where the following code successfully logs the context when using react-router-dom 4.0.0 , but logs undefined when using 5.0.1 .有一个问题,以下代码在使用react-router-dom 4.0.0时成功记录了上下文,但在使用5.0.1时记录了undefined

const { BrowserRouter, Route, Switch } = window.ReactRouterDOM;

const PropTypes = window.PropTypes;

class Main extends React.Component {
  static contextTypes = {
    router: PropTypes.object.isRequired,
  }

  render() {
    console.log("this.context.router");
    console.log(this.context);
    console.log(this.context.router);

    return <div>Main</div>;
  }
}

const App = () => (
  <BrowserRouter>
    <div>
      <Switch>
        <Route path="/" component={Main} />
      </Switch>
    </div>
  </BrowserRouter>
);

ReactDOM.render(<App />, document.getElementById('app'));

using: 4.0.0 (works): https://jsfiddle.net/2shm7awn/3/使用: 4.0.0 (有效): https : 4.0.0

using: 5.0.1 (doesn't work): https://jsfiddle.net/2shm7awn/2/使用: 5.0.1 (不起作用): https : //jsfiddle.net/2shm7awn/2/

using 5.0.1 and every other package up to date ( react / react-dom @ 16.9.0 - also doesn't work):使用5.0.1和所有其他最新包( react / react-dom @ 16.9.0 - 也不起作用):

https://jsfiddle.net/2shm7awn/5/ https://jsfiddle.net/2shm7awn/5/

I've done a fair amount of searching, and even if I missed something obvious in the docs, I think this could help some in the future.我已经进行了大量搜索,即使我遗漏了文档中的一些明显内容,我认为这在未来会有所帮助。

Is there something new with version 5 that I'm missing?版本 5 中是否有我遗漏的新内容?

I suppose the reason is that React Router 5 uses the new context API, which is different from the old one.我想原因是 React Router 5 使用了新的上下文 API,这与旧的有所不同。 You can find some information here: react router v5 and some points how to access it accessing context api您可以在这里找到一些信息: react router v5和一些点如何访问它访问上下文 api

But why do you need to access the context this way?但是为什么需要以这种方式访问​​上下文呢? Probably the problem can be solved in another way.也许这个问题可以用另一种方式解决。

Came across this when I had a inexplicable failure after upgrading from v4 to v5.当我从 v4 升级到 v5 后遇到莫名其妙的故障时遇到了这个问题。 So to add to @sergii-vorobei's answer for anyone it might help.因此,添加到@sergii-vorobei 对任何可能有帮助的人的回答中。

My issue was because one of the package dependencies from generating the routes was bundling react-router in its distributable.我的问题是因为生成路由的包依赖项之一是将 react-router 捆绑在其可分发文件中。 Since react-router depends on the singleton for supplying the correct context, the singleton for the main app router and routes did not match leading to the routes never receiving the context from the main app.由于 react-router 依赖于提供正确上下文的单例,主应用程序路由器和路由的单例不匹配导致路由永远不会从主应用程序接收上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM