【发布时间】: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();
和
<Router history = {history}>
登录后如何更改页面并修复错误
【问题讨论】:
-
听起来您需要花一些时间了解hooks 是什么,以及react-router 的工作原理。
-
简短总结:钩子用于函数组件主体 仅。您可能应该使用来自
react-router-dom的BrowserRouter,它会为您创建history对象。然后你可以在子组件中使用history(而不是App)。
标签: reactjs authentication react-router react-hooks