You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Router Dom登录成功后无法自动跳转至首页问题求助

Hey there! Let's get that login redirect sorted out for you. The problem here is all about how your routing logic triggers:

What's Going Wrong

Your current route rule (the path="" one) only kicks in when someone visits the root URL. But you're logging in from the /Login page—after you successfully set the user state, the browser stays on /Login because nothing tells it to navigate away. The root path redirect doesn't automatically fire when the user state changes if you're already on another route.


This is the cleanest approach—we'll add a navigation call right when login succeeds. Here's how:

  1. Update your Intro component to use React Router's useNavigate hook, so it can pass navigation functionality to your login handler:
// Inside Intro.jsx
import { useNavigate } from 'react-router-dom';

function Intro({ Login, Logout, error }) {
  const navigate = useNavigate();

  const handleLogin = (details) => {
    // Pass the navigate function to your Login method
    Login(details, navigate);
  };

  return (
    // Replace with your existing Intro markup, pass handleLogin to SignIn instead of Login
    <SignIn Login={handleLogin} error={error} />
  );
}
  1. Modify the Login function in App.js to accept and use the navigate parameter:
const Login = (details, navigate) => {
  console.log(details);
  if(details.username === guestUser.username && details.password === guestUser.password) {
    console.log("Logged in as guest");
    setUser({
      username: details.username,
    });
    // Jump to Home right after setting the user state
    navigate('/Home');
  } else {
    console.log("details do not match");
    setError("Details do not match.")
  }
}

That's it! Now when login succeeds, it'll immediately send the user to the Home page.


Fix 2: Auto-Redirect When User State Changes

If you'd rather not touch the Intro component, you can listen for changes to the user state and redirect automatically. You'll need to move your route logic inside a component that has access to React Router's hooks:

function App() {
  const guestUser = {
    username: "guest",
    password: "guest",
  }
  const [user, setUser] = useState({username: "", password: ""})
  const [error, setError] = useState("");

  const Login = details => {
    console.log(details);
    if(details.username == guestUser.username && details.password == guestUser.password) {
      console.log("Logged in as guest");
      setUser({
        username: details.username,
      });
    } else {
      console.log("details do not match");
      setError("Details do not match.")
    }
  }

  const Logout = () => {
    console.log("logout");
  }

  // Create an inner component that can use Router hooks
  const AppRoutes = () => {
    const navigate = useNavigate();
    const location = useLocation();

    useEffect(() => {
      // If user is logged in and we're still on the Login page, redirect to Home
      if (user.username !== "" && location.pathname === "/Login") {
        navigate('/Home');
      }
    }, [user, navigate, location]);

    return (
      <Routes>
        <Route path="/Login" element={<Intro Login={Login} Logout={Logout} error={error}/>} />
        <Route path="/Home" element={<Home user={user}/>}/>
        <Route path="" element={user.username !== "" ? <Navigate to="/Home" /> : <Navigate to="/Login"/>}/>
      </Routes>
    );
  };

  return (
    <div className="App">
      <Router>
        <AppRoutes />
      </Router>
    </div>
  );
}

Quick Note

Double-check your route path capitalization—you're using /Login (capital L) in your routes, so make sure any redirects match that exactly to avoid unexpected 404s.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 21:42:51