V6 React Router Dom Routes are not working



我正试图建立一个React寄存器并使用JWT令牌登录,但我遇到了麻烦。

当我点击注册按钮时,它应该会带我登录。从那里我应该可以登录并查看仪表板。

当我点击注册时,什么也没发生。我用useNavigate替换了useHistory,用navigate替换了.history.push,但仍然没有。

我的数据库使用MAMP。

App.js

import { BrowserRouter, Routes, Route } from "react-router-dom";
import Dashboard from "./components/Dashboard";
import Login from "./components/Login";
import Navbar from "./components/Navbar";
import Register from "./components/Register";

function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Login />} />
<Route path="/register" element={<Register />} />
<Route path="/dashboard" element={<><Navbar /><Dashboard /></>} />
</Routes>
</BrowserRouter>
);
}

export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import "bulma/css/bulma.css";
import axios from "axios";

axios.defaults.withCredentials = true;

ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);

Dashboard.js

/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useEffect } from 'react'
import axios from 'axios';
import jwt_decode from "jwt-decode";
import { useNavigate } from 'react-router-dom';

const Dashboard = () => {
const [name, setName] = useState('');
const [token, setToken] = useState('');
const [expire, setExpire] = useState('');
const [users, setUsers] = useState([]);
const navigate = useNavigate();

useEffect(() => {
refreshToken();
getUsers();
}, []);

const refreshToken = async () => {
try {
const response = await axios.get('http://localhost:3306/token');
setToken(response.data.accessToken);
const decoded = jwt_decode(response.data.accessToken);
setName(decoded.name);
setExpire(decoded.exp);
} catch (error) {
if (error.response) {
navigate("/");
}
}
}

const axiosJWT = axios.create();

axiosJWT.interceptors.request.use(async (config) => {
const currentDate = new Date();
if (expire * 1000 < currentDate.getTime()) {
const response = await axios.get('http://localhost:3306/token');
config.headers.Authorization = `Bearer ${response.data.accessToken}`;
setToken(response.data.accessToken);
const decoded = jwt_decode(response.data.accessToken);
setName(decoded.name);
setExpire(decoded.exp);
}
return config;
}, (error) => {
return Promise.reject(error);
});

const getUsers = async () => {
const response = await axiosJWT.get('http://localhost:3306/users', {
headers: {
Authorization: `Bearer ${token}`
}
});
setUsers(response.data);
}

return (
<div className="container mt-5">
<h1>Welcome Back: {name}</h1>
<table className="table is-striped is-fullwidth">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{users.map((user, index) => (
<tr key={user.id}>
<td>{index + 1}</td>
<td>{user.name}</td>
<td>{user.email}</td>
</tr>
))}

</tbody>
</table>
</div>
)
}

export default Dashboard

Login.js

import React, { useState } from 'react'
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

const Login = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [msg, setMsg] = useState('');
const navigate = useNavigate();

const Auth = async (e) => {
e.preventDefault();
try {
await axios.post('http://localhost:3306/login', {
email: email,
password: password
});
navigate("/dashboard");
} catch (error) {
if (error.response) {
setMsg(error.response.data.msg);
}
}
}

return (
<section className="hero has-background-grey-light is-fullheight is-fullwidth">
<div className="hero-body">
<div className="container">
<div className="columns is-centered">
<div className="column is-4-desktop">
<form onSubmit={Auth} className="box">
<p className="has-text-centered">{msg}</p>
<div className="field mt-5">
<label className="label">Email or Username</label>
<div className="controls">
<input type="text" className="input" placeholder="Username" value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
</div>
<div className="field mt-5">
<label className="label">Password</label>
<div className="controls">
<input type="password" className="input" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} />
</div>
</div>
<div className="field mt-5">
<button className="button is-success is-fullwidth">Login</button>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
)
}

export default Login

Navbar.js

import React from 'react'
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

const Navbar = () => {
const navigate = useNavigate();

const Logout = async () => {
try {
await axios.delete('http://localhost:3306/logout');
navigate("/");
} catch (error) {
console.log(error);
}
}

return (
<nav className="navbar is-light" role="navigation" aria-label="main navigation">
<div className="container">
<div className="navbar-brand">
<a className="navbar-item" href="https://bulma.io">
<img src="https://bulma.io/images/bulma-logo.png" width="112" height="28" alt="logo" />
</a>

<a href="/" role="button" className="navbar-burger burger" aria-label="menu" aria-expanded="false" data-target="navbarBasicExample">
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
</a>
</div>

<div id="navbarBasicExample" className="navbar-menu">
<div className="navbar-start">
<a href="/" className="navbar-item">
Home
</a>
</div>

<div className="navbar-end">
<div className="navbar-item">
<div className="buttons">
<button onClick={Logout} className="button is-light">
Log Out
</button>
</div>
</div>
</div>
</div>
</div>
</nav>
)
}

export default Navbar

Register.js

import React, { useState } from 'react'
import axios from "axios";
import { useNavigate } from "react-router-dom";

const Register = () => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confPassword, setConfPassword] = useState('');
const [msg, setMsg] = useState('');
const navigate = useNavigate();

const Register = async (e) => {
e.preventDefault();
try {
await axios.post('http://localhost:3306/users', {
name: name,
email: email,
password: password,
confPassword: confPassword
});
navigate("/");
} catch (error) {
if (error.response) {
setMsg(error.response.data.msg);
}
}
}

return (
<section className="hero has-background-grey-light is-fullheight is-fullwidth">
<div className="hero-body">
<div className="container">
<div className="columns is-centered">
<div className="column is-4-desktop">
<form onSubmit={Register} className="box">
<p className="has-text-centered">{msg}</p>
<div className="field mt-5">
<label className="label">Name</label>
<div className="controls">
<input type="text" className="input" placeholder="Name"
value={name} onChange={(e) => setName(e.target.value)} />
</div>
</div>
<div className="field mt-5">
<label className="label">Email</label>
<div className="controls">
<input type="text" className="input" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
</div>
<div className="field mt-5">
<label className="label">Password</label>
<div className="controls">
<input type="password" className="input" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} />
</div>
</div>
<div className="field mt-5">
<label className="label">Confirm Password</label>
<div className="controls">
<input type="password" className="input" placeholder="Confirm Password" value={confPassword} onChange={(e) => setConfPassword(e.target.value)} />
</div>
</div>
<div className="field mt-5">
<button className="button is-success is-fullwidth">Register</button>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
)
}

export default Register

我认为路线中不需要'/',您只需导航到"寄存器";以及";仪表板";。链接到外部页面时仅使用定位标记。对于内部导航,请使用链接标记:按钮为<Link to="about">About</Link>navigate()

下面的代码片段是根据我的代码修改的。在用户登录(未经授权(之前,请显示您的营销页面和登录/注册按钮。默认情况下显示营销页面,登录/注册按钮将导航到";输入";或类似的。*全包路线将捕捉到这一点,并显示您的登录/注册页面。此外,如果有人来自书签*"路线捕捉到了这一点,并引导他们注册,也许他们会跳过去到达预定目的地。

用户通过身份验证后,返回"仪表板"路由。

注意仪表板路由是如何嵌套的,并且有一个组件将它们全部封装起来(这对导航栏很好(。您将<Outlet/>放入该组件中,任何相邻的路由都将呈现出口所在的位置。此外,在这些路由中,导航是相对的。即你可以navigate(jobId)而不能navigate(`jobs/${jobId}`)

const unauthenticatedRoutes = (
<Routes>
<Route path="/" element={<MarketingWrapper />}>
<Route index element={<MarketingHome />
<Route path="*" element={<SignUpSignIn />} />
</Route>
</Routes>
)
const authenticatedRoutes = (
<Routes>
<Route path="/" element={<DashboardWrapper />}>
<Route index element={<Dashboard />
<Route path="*" element={<NoMatch />} />
<Route path="enter" element={<SignUpSignIn />} />
<Route path='signout' element={<SignOut signOut={signOut} />} />
<Route path="jobs" element={<JobsList jobId={jobId!} />}>
<Route path=":jobId" element={<JobPage />} />
<Route index element={<JobNew jobId={jobId!} />} />
</Route>
</Route>
</Routes>
)
return (
isAuthenticated ? authenticatedRoutes : unauthenticatedRoutes
)

相关内容

  • 没有找到相关文章

最新更新