尝试运行我的React应用程序时,我在浏览器中不断出现此错误:
TypeError: Cannot read property 'history' of undefined
LinkContainer.js
var href = this.context.router.history.createHref(typeof to === 'string' ? {
控制台显示此错误:
The context `router` is marked as required in `LinkContainer`, but its value is `undefined`.
我在Index.js中的所有内容周围都定义了<Router>
,并正确设置了LinkContainers。然后,我现在只有一条简单的路线。我在很多地方读到了它的React-Router v4在React-Router-Bootstrap中与LinkContainer一起使用时会引起问题,但是在v4中没有解决方案,我应该降级到v3,或者我完全是在这里缺少某些东西来允许这样做工作?
我正在使用以下软件包版本:
"react": "^16.8.3",
"react-bootstrap": "^1.0.0-beta.5",
"react-dom": "^16.8.3",
"react-router": "^4.3.1",
"react-router-bootstrap": "^0.24.4",
"react-router-dom": "^4.4.0-beta.6",
我有以下代码:
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter as Router } from "react-router-dom";
ReactDOM.render(<Router><App /></Router>, document.getElementById("root"));
serviceWorker.unregister();
App.js
import React, { Component } from "react";
import { Navbar, Nav, NavItem } from "react-bootstrap";
import { LinkContainer } from "react-router-bootstrap";
import "./App.css";
import Routes from "./Routes";
class App extends Component {
render() {
return (
<div className="App container">
<Navbar fluid collapseOnSelect>
<Navbar.Brand>
<LinkContainer to="/home">
<NavItem>Ness</NavItem>
</LinkContainer>
</Navbar.Brand>
<Navbar.Toggle />
<Navbar.Collapse>
<Nav pullRight>
<LinkContainer to="/signup">
<NavItem>Signup</NavItem>
</LinkContainer>
<LinkContainer to="/login">
<NavItem>Login</NavItem>
</LinkContainer>
</Nav>
</Navbar.Collapse>
</Navbar>
<Routes />
</div>
);
}
}
export default App;
Routes.js
import React from "react";
import { Route, Switch } from "react-router-dom";
import Home from "./containers/Home";
export default () =>
<Switch>
<Route path="/home" component={Home} />
</Switch>;