history.push 带有注销图标
history.push with Logout Icon
我使用材质 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 (evaluating 'props.history.push')
App.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>
);
}
如何解决重定向问题?
我会尝试使用 useHistory
钩子,来自文档:
The useHistory
hook gives you access to the history instance that you may use to navigate.
喜欢以下内容:
import { useHistory } from 'react-router-dom';
const YourComponent = () => {
let history = useHistory();
const logout = () => {
localStorage.removeItem('token');
history.push('/login');
}
/* rest of your component code */
return (
{ /* your other elements */ }
<ExitToAppIcon onClick={logout}></ExitToAppIcon>
)
}
希望对您有所帮助!
我使用材质 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 (evaluating 'props.history.push')
App.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>
);
}
如何解决重定向问题?
我会尝试使用 useHistory
钩子,来自文档:
The
useHistory
hook gives you access to the history instance that you may use to navigate.
喜欢以下内容:
import { useHistory } from 'react-router-dom';
const YourComponent = () => {
let history = useHistory();
const logout = () => {
localStorage.removeItem('token');
history.push('/login');
}
/* rest of your component code */
return (
{ /* your other elements */ }
<ExitToAppIcon onClick={logout}></ExitToAppIcon>
)
}
希望对您有所帮助!