1 回答
TA贡献1862条经验 获得超7个赞
大多数教程使用localStorageorcookie是因为您希望即使在用户刷新页面后也保留登录状态,这样他们就不必每次都重新登录。但要回答你的问题,你可以这样做:
import React, { useState } from "react";
import { Route, Redirect, BrowserRouter } from "react-router-dom";
import "./style.css";
import axios from "axios";
function yourLoginPostApi() {
return new Promise(r => setTimeout(() => r(true), 1000));
}
function Login({ onSuccess }) {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
let [loading, setLoading] = useState(false);
const onChangeUsername = e => {
setUsername(e.target.value);
};
const onChangePassword = e => {
setPassword(e.target.value);
};
const onSubmit = async e => {
const user = {
username: username,
password: password
};
e.preventDefault();
setLoading(true);
// Uncomment this line and remove the next one since it's a fake api call
// let response = await axios.post("http://localhost:5000/users/login", user);
let response = await yourLoginPostApi();
setLoading(false);
onSuccess(response);
};
return (
<div className="Login">
<h2>Traffic scan admin panel</h2>
<div className="LoginInfo-Logins">
<form>
<input
type="text"
required
className=""
value={username}
onChange={onChangeUsername}
placeholder="Username*"
/>
<input
type="text"
required
className=""
value={password}
onChange={onChangePassword}
placeholder="Password*"
/>
</form>
</div>
<button onClick={onSubmit}>SIGN IN</button>
<div>{loading && "Please wait..."}</div>
</div>
);
}
function PrivateRoute({ children }) {
let [loggedIn, setLoggedIn] = useState(false);
return loggedIn ? (
<div>
{children}
<button onClick={() => setLoggedIn(false)}>log out</button>
</div>
) : (
<Login onSuccess={() => setLoggedIn(true)} />
);
}
export default function App() {
return (
<BrowserRouter>
<PrivateRoute>
<div>Stuff only a logged in user should see</div>
</PrivateRoute>
</BrowserRouter>
);
}
添加回答
举报