You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

React项目中点击登录按钮后无法从Login页面跳转到/profile页面,如何修复?

Fixing Login Redirect Issue in React Component

Hey, let's break down why your login button isn't redirecting to the /profile page as expected—here are the key issues and how to fix them:

1. Unhandled Form Default Submission Behavior

When you submit an HTML form, it defaults to reloading the page. Even if you call history.push(), the page refresh will wipe out that navigation action before it can take effect. You need to prevent this default behavior to let the React Router navigation work.

2. Incorrect Input Value Retrieval

Your code tries to access loginFormUser.username.value—but the input element doesn't have a username property. You should directly get the value from the input element itself.

3. Redundant Event Listener

You’re using the form’s onSubmit handler and adding a click listener to the submit button inside checkLogin. This is unnecessary, causes event conflicts, and adds a new listener every time the component renders (leading to memory leaks over time).


Fixed Code

import React from "react";
import { useHistory } from "react-router-dom";

function Login() {
  const history = useHistory();

  function checkLogin(e) {
    // Stop the form from reloading the page
    e.preventDefault();
    
    // Get input values the right way
    const username = document.getElementById("login-form-user").value;
    const password = document.getElementById("login-form-password").value;

    // Handle navigation based on credentials
    if (username === "toilacoder" && password === "123456") {
      history.push("/profile");
    } else {
      history.push("/home");
    }
  }

  return (
    <form onSubmit={checkLogin}>
      <h2>Please login to get access to your profile.</h2>
      <input type="text" placeholder="Username" id="login-form-user" />
      <input type="password" placeholder="Your password" id="login-form-password" />
      <button id="login-form-submit" type="submit">
        Login
      </button>
    </form>
  );
}

export default Login;

Key Changes Explained:

  • Added e.preventDefault() in checkLogin to block the page reload triggered by form submission.
  • Fixed input value retrieval to use .value directly on the input elements.
  • Removed the redundant click event listener on the submit button—the form’s onSubmit already triggers when the button is clicked (or when the user presses Enter in an input field).

内容的提问来源于stack exchange,提问作者Adam

火山引擎 最新活动