React:按钮链接到另一个页面



我有一个登录页面,后端和前端已经准备好将所有数据连接在一起,但我的问题是:我想点击登录按钮,然后重定向到另一个页面!我知道如何使用useNavigate重定向到另一个页面,但主要问题是:如果用户名和密码正确,则必须链接到另一页面!当按钮onclick为时,不会自动连接!

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

import React, {useState} from "react";
import {NavLink, useNavigate} from "react-router-dom";
import axios from "axios";
import "./LoginPage.css"
export default function LoginPage() {
const [username, setUsername] = useState("")
const [password, setPassword] = useState("")
const [me, setMe] = useState("")
const navigate = useNavigate();
function handleLogin(){
axios.get("api/user/login",{auth: {username, password}})
.then(response => response.data)
.then((data) => setMe(data))
.then(() => setUsername(""))
.then(() => setPassword(""))
.catch(() => alert("Sorry, Username or Password is wrong or Empty!"))

}
function handleLogout(){
axios.get("api/user/logout")
.then(() => setMe(""))
}

return (
<div className={"login-main"}>
<NavLink to={"/question"}>zur Question Page</NavLink>
<h1>Login Page</h1>
<h3>Login</h3>
<input placeholder={"Username ..."} value={username} onChange={event => setUsername(event.target.value)}/>
<input placeholder={"Password ..."} type={"password"} value={password} onChange={event => setPassword(event.target.value)}/>
<button onClick={() => {
handleLogin();
{navigate("/question")}
}}>Login</button>

}
</div>

)
}

在handleLogin函数内部移动navigate("/question")。在那里你需要检查一下这是一个好的登录名和密码吗?如果是,那么您可以导航。我会让handlelogin成为一个等待结果的异步函数。如果这是一个好的结果,那么你可以转到登录,如果不是,那么你可能会给用户一个错误消息。它目前写在onclick函数中的地方,它不知道登录方法,所以它没有什么可等待的,所以只要你点击它就会执行。

编辑:我还建议在输入字段中添加验证。这样,您就可以禁用用户的按钮,这样,如果输入字段无效,用户甚至无法单击按钮。

var loginSuccessful = false;
const handleLogin = async () => {
// create an async/await function to make the db call
await axios.get("api/user/login",{auth: {username, password}}).then((response) => { // wait for api call
setPost(response.data);
setUsername("");
setPassword("");
loginSuccessful = true; // set login to true or false based on result
}).catch(error => {
console.log(error);
loginSuccessful = false;
});
// create a boolean check if the login was successful or not. You need to make the api call to login, 
// that api call will return with an ok response or an error response
// if the api call returned with a 200 response then it was successful and you can navigate
// if you have the navigate not wrapped with an if check then it will still route whenever it gets here
// so this check is very important
if (loginSuccessful) { 
navigate("/question")
} else {
// if the api call returned with some other 400-500 ish reponse then it failed and you can display an error message
} 
}

如果您只是将导航移动到函数,那么它将具有相同的结果。你需要等待api调用完成,然后根据你得到的响应,你可以选择是否登录。如果响应不正确,则显示错误。如果响应良好,则可以导航。

您可以让handleClick()返回一个布尔值来确定登录是否成功:

function handleLogin(){
let success;
axios.get("api/user/login",{auth: {username, password}})
.then(response => response.data)
.then((data) => {
setMe(data);
success = true;
})
.then(() => setUsername(""))
.then(() => setPassword(""))
.catch(() => {
alert("Sorry, Username or Password is wrong or Empty!");
success = false ;
});
return success;      
}

然后,您可以将其绑定到一个三元运算符,以有条件地将字符串传递给navigate():

navigate(handleClick() ? '/question' : '/someOtherComponent');

希望这能有所帮助。

最新更新