javascript 为什么不工作,但console. log("身份验证成功!");< Navigate to="" />正在工作 is working

2skhul33  于 2023-02-28  发布在  Java
关注(0)|答案(1)|浏览(96)
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语句中不起作用,为什么会发生这种情况?

o2rvlv0m

o2rvlv0m1#

不能像这样从回调中返回JSX,并期望它被呈现和做任何事情。Navigate组件发出声明性导航操作,必须使用组件呈现来呈现,例如从函数组件返回的JSX的一部分。
如果您想从回调调用导航操作,则使用useNavigate钩子并发出命令式导航操作。
示例:

import { useNavigate } from "react-router-dom"; // <-- import hook

const Login = () => {
  const navigate = useNavigate(); // <-- call hook

  ...

  const handleSubmit = (event) => {
    event.preventDefault();
    if (username === "name" && password === "123") {
      // Authentication successful - redirect to home page
      console.log("Authentication successful!");
      navigate("/home"); // <-- issue navigation action
    } else {
      // Authentication failed - display an error message
      console.log("Authentication failed!");
    }
  };

  ...

相关问题