【问题标题】:React.js change pageReact.js 更改页面
【发布时间】:2021-10-15 00:28:31
【问题描述】:

我编写了一个登录面板,需要通过history.Push() 更改页面,但出现错误:

React Hook "useHistory" 不能在顶层调用。 React Hooks 必须在 React 函数组件或自定义 React Hook 函数中调用

    import react from 'react';
    import{landingPage, adminPage} from './components';
    import { Route,Router, Switch } from 'react-router-dom';
    import {useHistory} from 'react-router-dom';
    import {routes} from './components/routes'

    const history = useHistory();
    class App extends react.Component{
      handlepageChange = (activePage) => {
        history.push(activePage);
      }
      render(){
        const {landing, admin} = routes;
        return(
          <div className="App">
            <Router history ={history}>
              <Switch>
                <Route exact path = {landing.path}>
                  <landingPage handlepageChange = {this.handlepageChange}/>
                </Route>
                <Route exact path={admin.path}>
                  <adminPage handlepageChange ={this.handlepageChange}/>
                </Route>
              </Switch>
            </Router>
          </div>
        )
      }
    }
    
    export default App;

错误出现在

const history = useHistory();

&lt;Router history = {history}&gt;

登录后如何更改页面并修复错误

【问题讨论】:

  • 听起来您需要花一些时间了解hooks 是什么,以及react-router 的工作原理。
  • 简短总结:钩子用于函数组件主体 。您可能应该使用来自react-router-domBrowserRouter,它会为您创建history 对象。然后你可以在子组件中使用history(而不是App)。

标签: reactjs authentication react-router react-hooks


【解决方案1】:

您可以在类组件中使用this.props.history.push(activePage) 导航到其他组件

【讨论】:

  • 他们在这里做不到。 history 必须通过某种东西放入道具中,它不只是神奇地出现。在给出简单答案之前,需要解决 OP 代码中的基本误解。
猜你喜欢
  • 2021-03-31
  • 1970-01-01
  • 2020-04-11
  • 2021-07-15
  • 2021-10-19
  • 2011-05-30
  • 2013-09-21
  • 2020-06-23
  • 1970-01-01
相关资源
最近更新 更多