在 React 上使用 useHistory

时间:2021-06-29 09:04:56

标签: reactjs react-router

我是 React 的初学者,正在尝试自学。我有这个代码,我想使用 useHistory 导航到登录页面,但我似乎无法让它工作。希望您能够帮助我。这是我的代码如下:

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

const App = () => {
    let history = useHistory();
    
    const MoveToLogin = () => {
        history.push('./container/Login');
    }

    return (
        <div>
            <button className='btn' text='User Login' onClick=. 
            {MoveToLogin}>Login</button>
        </div>
    );
}

export default App;

3 个答案:

答案 0 :(得分:1)

我希望你为指定的路径定义了路由

      <Router>
        <Route path="/container/Login" exact component={LoginComponent} />
      </Router>

转移到登录功能时不需要点。

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

const App = () => {
    let history = useHistory();
    
    const MoveToLogin = () => {
        history.push('/container/Login'); // Here you don't need dot ./container
    }

    return (
        <div>
            <button className='btn' text='User Login' onClick=. 
            {MoveToLogin}>Login</button>
        </div>
    );
}

export default App;

答案 1 :(得分:0)

  1. 首先你需要添加从'react-router-dom'导入的Provider 'Router'
  2. 在路由文件中定义路由和相应的组件。
  3. 您只能在 Provider Router 的子代中使用历史记录。
  4. 使用 history.push('/login') 导航到路由。此处不要提供组件文件的相对路径。使用你想在浏览器 url 中显示的路由

答案 2 :(得分:0)

我玩过并做了更多关于 useHistory 的研究。我能够让它工作。它已导航到一个新组件。请在下面找到我的解决方案。希望它可以帮助其他有同样问题的人。

import UserLogin from "./pages/UserLogin";

const ButtonLogin = () => {
  let history = useHistory();
  const MoveToLogin = () => {
    history.push('/pages/UserLogin');
  }
  return (
    <div><button className='btn btn-primary' onClick={MoveToLogin}>Login</button></div>
  );
}
const App = () => {
  return (
    <div>
      <Router>
        <Route path="/pages/UserLogin" exact component={UserLogin} />
        <Route path="/" exact component={ButtonLogin} />
      </Router>
    </div>
  );
}

export default App;

另请参阅此答案以获取更多信息。 Cannot read property 'push' of undefined for react use history