React 路由似乎有效,但它不呈现页面

React routing seems to work but it doesn't render the page

当我单击按钮时,URL 发生变化并在控制台中打印 'user exists',但页面为空白且未显示组件。我已经尝试找出问题 2 天了,但我似乎找不到解决方案,希望这里有人可以提供帮助。 这是代码:


import { Fragment, useState } from "react";
import { Route, Link, useHistory } from "react-router-dom";
import LoggedUser from "../pages/LoggedUser";

const ExitingUserButton = () => {
    const [existingUser, setExistingUser] = useState(false);
    let history = useHistory();

    const loginHandler = () => {
        setExistingUser(true);
        console.log('user exists');
        history.push('/logged-user');
    };

    return (
        <Fragment>
            {!existingUser ?
                <Link type='Link' onClick={loginHandler} to='/logged-user'>  existing user </Link>
                :
                <Route path='/logged-user' exact>
                    <LoggedUser />
                </Route>
            }
        </Fragment>
    )
}
export default ExitingUserButton;

   
import { Fragment } from "react";

const LoggedUser = () => {
    return (
        <Fragment>
            <h1>Hello, user!</h1>
        </Fragment>
    );
};

export default LoggedUser;

你应该用 Switch 包裹你的 Routes。 检查文档 https://v5.reactrouter.com/web/guides/quick-start

<Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/users">Users</Link>
            </li>
          </ul>
        </nav>

        {/* A <Switch> looks through its children <Route>s and
            renders the first one that matches the current URL. */}
        <Switch>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/users">
            <Users />
          </Route>
          <Route path="/">
            <Home />
          </Route>
        </Switch>
      </div>
    </Router>