Why <Navigate to="" /> is not working but console.log("Authentication successful!"); is working

huangapple go评论69阅读模式
英文:

Why <Navigate to="" /> is not working but console.log("Authentication successful!"); is working

问题

The &lt;Navigate to=&quot;/home&quot; /&gt; is not working within the if statement because it's not being returned in a way that can affect the navigation. In React, you typically handle navigation using routing components like react-router-dom outside of the rendering logic.

To resolve this issue, you can use a different approach to handle navigation upon successful authentication. Here's how you can modify your code:

import Typewriter from "typewriter-effect";
import { useHistory } from "react-router-dom"; // Import useHistory hook from react-router-dom
import { useState } from "react";

const Login = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const history = useHistory(); // Initialize the useHistory hook

  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 - use history to navigate to the home page
      console.log("Authentication successful!");
      history.push("/home"); // Use history.push to navigate
    } else {
      // Authentication failed - display an error message
      console.log("Authentication failed!");
    }
  };

  return (
    <div className="flex justify-center items-center w-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;

In this modified code, we use the useHistory hook from react-router-dom to handle navigation. When authentication is successful, we use history.push to navigate to the home page. This way, you can navigate without the need for the <Navigate> component inside an if statement.

英文:
import Typewriter from &quot;typewriter-effect&quot;;
import { Navigate } from &quot;react-router-dom&quot;;
import { useState } from &quot;react&quot;;

const Login = () =&gt; {
  const [username, setUsername] = useState(&quot;&quot;);
  const [password, setPassword] = useState(&quot;&quot;);

  const handleUsernameChange = (event) =&gt; {
    setUsername(event.target.value);
  };

  const handlePasswordChange = (event) =&gt; {
    setPassword(event.target.value);
  };

  const handleSubmit = (event) =&gt; {
    event.preventDefault();
    if (username === &quot;name&quot; &amp;&amp; password === &quot;123&quot;) {
      // Authentication successful - redirect to home page
      console.log(&quot;Authentication successful!&quot;);
      return &lt;Navigate to=&quot;/home&quot; /&gt;;
    } else {
      // Authentication failed - display an error message
      console.log(&quot;Authentication failed!&quot;);
    }
  };

  return (
    &lt;div className=&quot;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&quot;&gt;
      &lt;div className=&quot; w-[500px] h-[490px] text-white bg-black/20 rounded-2xl&quot;&gt;
        &lt;div className=&quot;w-[400px] py-10 mx-auto&quot;&gt;
          &lt;form onSubmit={handleSubmit} className=&quot;text-black&quot;&gt;
            &lt;label&gt;
              Username:
              &lt;input
                type=&quot;text&quot;
                value={username}
                onChange={handleUsernameChange}
              /&gt;
            &lt;/label&gt;
            &lt;br /&gt;
            &lt;label&gt;
              Password:
              &lt;input
                type=&quot;password&quot;
                value={password}
                onChange={handlePasswordChange}
              /&gt;
            &lt;/label&gt;
            &lt;br /&gt;
            &lt;button
            &gt;
              Submit
            &lt;/button&gt;
          &lt;/form&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  );
};

export default Login;

The console.log is working for both if condition but &lt;Navigate to=&quot;/home&quot; \&gt; is not working is there any way to resolve this error, tried return &lt;Navigate to=&quot;/home&quot; \&gt; without using if statement and it works, its not working in if statement, why this happens? ‎ ‎

答案1

得分: 0

无法从回调函数中返回JSX,并期望它被渲染并执行任何操作。Navigate 组件发出一个声明式导航操作,并必须与组件渲染一起使用,例如从函数组件返回的JSX 的一部分。

如果您想从回调中调用导航操作,可以使用 useNavigate 钩子并发出一个命令式导航操作。

示例:

import { useNavigate } from "react-router-dom"; // 导入钩子

const Login = () => {
  const navigate = useNavigate(); // 调用钩子

  ...

  const handleSubmit = (event) => {
    event.preventDefault();
    if (username === "name" && password === "123") {
      // 认证成功 - 重定向到主页
      console.log("认证成功!");
      navigate("/home"); // 发出导航操作
    } else {
      // 认证失败 - 显示错误消息
      console.log("认证失败!");
    }
  };

  ...
英文:

You can't return JSX from a callback like this and expect it to be rendered and do anything. The Navigate component issues a declarative navigation action and must be rendered with the component render, e.g. part of the returned JSX from the function component.

If you want to invoke a navigation action from a callback then use the useNavigate hook and issue an imperative navigation action.

Example:

import { useNavigate } from &quot;react-router-dom&quot;; // &lt;-- import hook

const Login = () =&gt; {
  const navigate = useNavigate(); // &lt;-- call hook

  ...

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

  ...

huangapple
  • 本文由 发表于 2023年2月27日 15:44:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75577874.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定