import Typewriter from "typewriter-effect";
import { Navigate } from "react-router-dom";
import { useState } from "react";
const Login = () => {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const handleUsernameChange = (event) => {
setUsername(event.target.value);
};
const handlePasswordChange = (event) => {
setPassword(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
if (username === "name" && password === "123") {
// Authentication successful - redirect to home page
console.log("Authentication successful!");
return <Navigate to="/home" />;
} else {
// Authentication failed - display an error message
console.log("Authentication failed!");
}
};
return (
<div className="flex justify-center items-center w-full h-screenw-full h-screen bg-gradient-to-r from-lime-700 via-orange-900 to-red-800">
<div className=" w-[500px] h-[490px] text-white bg-black/20 rounded-2xl">
<div className="w-[400px] py-10 mx-auto">
<form onSubmit={handleSubmit} className="text-black">
<label>
Username:
<input
type="text"
value={username}
onChange={handleUsernameChange}
/>
</label>
<br />
<label>
Password:
<input
type="password"
value={password}
onChange={handlePasswordChange}
/>
</label>
<br />
<button
>
Submit
</button>
</form>
</div>
</div>
</div>
);
};
export default Login;
console.log
对两个if条件都有效,但<Navigate to="/home" \>
不起作用有什么方法可以解决这个错误,尝试返回<Navigate to="/home" \>
而不使用if语句,它起作用,它在if语句中不起作用,为什么会发生这种情况?
1条答案
按热度按时间o2rvlv0m1#
不能像这样从回调中返回JSX,并期望它被呈现和做任何事情。
Navigate
组件发出声明性导航操作,必须使用组件呈现来呈现,例如从函数组件返回的JSX的一部分。如果您想从回调调用导航操作,则使用
useNavigate
钩子并发出命令式导航操作。示例: