我正在学习React路由器,并已将其添加到导航栏中,并在另一个文件中声明了路由。链接不是重定向到给定的路径,而是。当我尝试提供标签时,它可以完美地工作。我什至尝试在Nav组件中实现路由,但这也不起作用。我可能会使用正确的方式。这是问题和代码的屏幕截图。
Index.js
import ReactDOM from 'react-dom';
import React, { Component } from 'react'
import Nav from './Nav'
import App from './App';
import {
BrowserRouter,
Switch,
Route,
Redirect
} from "react-router-dom";
import Login from './Login';
import Signup from './Signup';
import Home from './Home';
import Notfound from './Notfound';
import Country from './Country'
import Fire from './Fire';
export default class Auth extends Component {
constructor() {
super();
this.state = {
user: {}
}
this.authListener = this.authListener.bind(this);
this.logout=this.logout.bind(this);
}
componentDidMount() {
this.authListener();
}
authListener = () => {
Fire.auth().onAuthStateChanged((user) => {
console.log(user);
if (user) {
this.setState({ user });
console.log("if user" + user)
} else {
this.setState({ user: null });
console.log("user not logged in")
}
});
}
logout= () => {
Fire.auth().signOut();
}
render() {
return (
<div>
<Nav user={this.state.user} logout={this.logout}/>
<BrowserRouter>
<Switch>
<Route path="/signup">
<Signup />
</Route>
<Route path="/login">
<Login />
</Route>
<Route exact path="/data">
<App />
</Route>
<Route path="/data/:id">
<Country />
</Route>
<Route exact path="/">
<Home />
</Route>
<Route path="/not-found" component={Notfound} />
<Redirect to="/not-found" />
</Switch>
</BrowserRouter>
</div>
)
}
}
ReactDOM.render(
<Auth />
,
document.getElementById('root')
);
Nav.js
import React from 'react'
import Navbar from "react-bootstrap/Navbar";
import Button from "react-bootstrap/Button";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
export default function Nav(props) {
return (
<div>
<Router>
<Navbar bg="dark" variant="dark">
<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<Link to="/">Home</Link>
</li>
{!props.checkUser ?
[<li class="nav-item">
<Link to="/login">Login</Link>
</li>,
<li class="nav-item">
<Link to="/signup">Register</Link>
</li>] :
[<li>
<Link to="/data">Data</Link>
</li>,
<li>
<Link onClick={props.logout}>Logout</Link>
</li>]}
</ul>
</Navbar.Brand>
</Navbar>
</Router>
</div>
)
}