登录后反应路由器未正确路由

时间:2021-01-22 18:05:38

标签: reactjs routes react-router-dom

function Login() {
    const history = useHistory();
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    const signIn = e => {
        e.preventDefault();

        auth
            .signInWithEmailAndPassword(email, password)
            .then(auth => {
                history.push('/home')
            })
            .catch(error => alert(error.message))
    }

    const register = e => {
        e.preventDefault();

        auth
            .createUserWithEmailAndPassword(email, password)
            .then((auth) => {
                // it successfully created a new user with email and password
                if (auth) {
                    history.push('/home')
                }
            })
            .catch(error => alert(error.message))
    }

    return (
        <div className='login'>
            <Link to='/'>
                <img
                    className="login__logo"
                     src='' />
            </Link>

            <div className='login__container'>
                <h1>Ticket System</h1>

                <form>
                    <h5>E-mail</h5>
                    <input type='text' value={email} onChange={e => setEmail(e.target.value)} />

                    <h5>Password</h5>
                    <input type='password' value={password} onChange={e => setPassword(e.target.value)} />

                    <button type='submit' onClick={signIn} className='login__signInButton'>Sign In</button>
                </form>

                <p>
                
                </p>

                <button onClick={register} className='login__registerButton'>Register Your Account</button>
            </div>
        </div>
    )
}


function App() {

  return (
    <Router>
      <div className="app">
      <Login />
        <Switch>

        <Route path="/">
            <Login />
          </Route>
          <Route path="/home">
            <Home />
          </Route>

        </Switch>
      </div>
    </Router>
  );
}

import React from "react";


function Home() {
  return (
    <div className="home">
        <h1>hello world</h1>
  
    </div>
  );
}

export default Home;

这些是我登录时的应用程序、主页、登录 js 文件,它没有路由到主页不知道发生了什么。单击登录后,我试图转到“/home”,我正在使用的帐户已注册。登录时,路由 url 确实更改为 /home,但不会转到其中的内容,只是停留在登录页面上

1 个答案:

答案 0 :(得分:1)

当您的项目在浏览器中运行时,路由器会找到特定路径 所以你应该在一个路径中添加 exact

function App() {

  return (
    <Router>
      <div className="app">
      <Login />
        <Switch>

        <Route path="/">
            <Login />
          </Route>
          <Route exact path="/home">
            <Home />
          </Route>

        </Switch>
      </div>
    </Router>
  );
}