history.push 与注销图标

我正在使用材质 ui 图标作为注销按钮。我这样使用它:


function logout(props:any){

  localStorage.removeItem("token");

  return(

    <Redirect to="/login" />

  )

  //props.history.push("/login");

}


 <ExitToAppIcon onClick={logout}></ExitToAppIcon>

当我单击该图标时,令牌会从 localStorage 中删除,但它不会重定向到/login页面,如果我使用该行props.history.push("/login");而不是Redirect,页面会崩溃并给我这个错误:


TypeError: undefined is not an object (评估'props.history.push')


应用程序.tsx:



const token = localStorage.getItem('token');


export default function App() {

  return (

    <div>

      <BrowserRouter>

      <Switch>

      <Route exact path='/' component= {HomePage}></Route>

      <Route path='/login' component= {LoginPage}></Route>

      <PrivateRoute

      path='/panel'

      isAuthenticated={token}

      component={PanelHomePage}

      />

      <Redirect from='*' to='/404' />

      </Switch>

      </BrowserRouter>

    </div>

  );

}

如何解决重定向问题?


慕虎7371278
浏览 124回答 1
1回答

慕标5832272

我会尝试使用useHistory文档中的钩子:该useHistory钩子使您可以访问可用于导航的历史实例。如下所示:import { useHistory } from 'react-router-dom';const YourComponent = () => {&nbsp; &nbsp;let history = useHistory();&nbsp; &nbsp;const logout = () => {&nbsp; &nbsp; &nbsp; localStorage.removeItem('token');&nbsp; &nbsp; &nbsp; history.push('/login');&nbsp; &nbsp;}&nbsp; &nbsp;/* rest of your component code */&nbsp; &nbsp;return (&nbsp; &nbsp; &nbsp; &nbsp;{ /* your other elements */ }&nbsp; &nbsp; &nbsp; &nbsp;<ExitToAppIcon onClick={logout}></ExitToAppIcon>&nbsp; &nbsp;)}我希望这有帮助!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript