【问题标题】:Using useHistory on React在 React 上使用 useHistory
【发布时间】:2021-09-11 11:37:59
【问题描述】:

我是 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;

【问题讨论】:

    标签: reactjs react-router


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

    【讨论】:

      【解决方案2】:

      我玩过并做了更多关于 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

      【讨论】:

        【解决方案3】:

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

              <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;
        

        【讨论】:

          猜你喜欢
          • 2020-07-29
          • 2022-01-24
          • 2021-02-26
          • 2021-10-07
          • 1970-01-01
          • 2020-02-25
          • 2021-04-08
          • 2020-06-09
          • 1970-01-01
          相关资源
          最近更新 更多