嗨,我正在使用React Router来加载组件。它一直给我一个错误,说
您不应在
<Router>
之外使用<Link>
当用户首次访问页面时,我希望他们进入登录页面。成功登录并加载主页后,我在主页上有一个导航栏组件。如何嵌套路由?我遇到了麻烦,请帮忙。
app.js
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Navbar from "./components/Navbar";
import Landing from "./components/Landing";
import Login from "./components/Login";
import Register from "./components/Register";
import Course from "./components/AddCourse";
import Homepage from "./components/Homepage";
import AddCourse from "./components/AddCourse";
import SearchCourse from "./components/SearchCourse";
import SearchItem from "./components/SearchItem";
import Profile from "./components/Profile";
class App extends Component {
render() {
return (
<Router>
<div className="App">
<Route path="/login" component={Login} exact={true} />
<Route path="/register" component={Register} exact={true} />
<div>
<Switch>
<Route path="/homepage" component={Homepage} exact={true} />
<Route path="/" component={SearchCourse} exact={true} />
<Route path="/profile" component={Profile} exact={true} />
</Switch>
</div>
</div>
</Router>
);
}
}
export default App;
导航栏
import React, { Component } from "react";
import jwt_decode from "jwt-decode";
import { Link, withRouter } from "react-router-dom";
class Navbar extends Component {
constructor() {
super();
this.state = {
name: "",
email: ""
};
}
componentDidMount() {
const token = localStorage.usertoken;
const decoded = jwt_decode(token);
this.setState({
name: decoded.name,
email: decoded.email
});
}
logOut(event) {
event.preventDefault();
localStorage.removeItem("usertoken");
this.props.history.push("/");
}
render() {
return (
<ul style={navBarStyle} id="sidenav-1" className="sidenav sidenav-fixed">
<li>
<img style={imageStyle} src="" alt="Avatar" />
</li>
<li>
<Link to="/profile">
<i style={linkStyle} class="material-icons ">
person
</i>
</Link>
</li>
<li>
<a href="https://twitter.com/MaterializeCSS" target="_blank">
<i style={linkStyle} class="material-icons ">
book
</i>
</a>
</li>
<li>
<Link to="/searchCourses">
<i style={linkStyle} class="material-icons">
search
</i>
</Link>
</li>
<li style={linkStyle}>
<a href="" onClick={this.logOut.bind(this)}>
<i style={linkStyles} class="fas fa-sign-out-alt" />
</a>
</li>
</ul>
);
}
}
主页
import React, { Component } from "react";
import { Link, withRouter } from "react-router-dom";
import jwt_decode from "jwt-decode";
import Navbar from "./Navbar";
import CourseItem from "./CourseItem";
class Homepage extends Component {
componentDidMount() {
document.title = "Dashboard";
}
render() {
return (
<div>
<Navbar />
<div className="container">
<div>
<h3>Dashboard</h3>
<hr />
</div>
<div className="col" />
{/* {this.props.children} */}
</div>
</div>
);
}
}
export default Homepage;
Navbar
。你应该在那里使用export default withRouter(Navbar)
进行导出。 - flppv