如何从 React 中的函数重定向到新页面? [英] How to redirect to a new page from a function in React?
问题描述
现在我在反应中有这个函数,我正在使用它返回登录并检查重置我正在使用该函数的 localStorage 值,而不是因为使用它我无法重置本地存储值.功能如下:-
Right now I have this function in react and I am using it to go back to login and also to check reset the localStorage value for which I am using the function and not since using that I cannot reset local storage value. The function is below:-
logout(){
localStorage.clear();
console.log("cliasdk");
return(
<Redirect to="/login"/>
)
}
这在点击 div 时执行,但我无法转到/login 页面.如何做?
This gets executed on clicking a div but I am not able to go to the /login page.How to do it?
推荐答案
如果您使用 react-router-dom
包,您可以使用路由器包装您的组件,然后您就可以重定向用户以编程方式,就像这样 this.props.history.push('/login')
.
If you use the react-router-dom
package you can wrap your component with a router and then you have the ability to redirect the user programmatically, like so this.props.history.push('/login')
.
例如:
import {withRouter} from 'react-router-dom';
class Component extends React.component {
constructor(props){
}
componentDidMount(){
this.props.history.push('/login');
}
}
export default withRouter(Component);
参见:https://www.npmjs.com/package/react-router-dom.
这篇关于如何从 React 中的函数重定向到新页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!