用户注销后,我希望页面导航回到主屏幕'/'
。我正在尝试使用this.props.history.push('/')
,但是该页面保留在当前的个人资料页面/profile#signout
上,并读取错误Cannot read property 'props' of undefined
。
这是我的logOutUser()函数的代码。我正在使用Firebase注销。
logOutUser(){
var tempname = login.getUser();
firebase
.auth()
.signOut()
.then(function() {
alert("Goodbye " + tempname + "!");
this.props.history.push('/');
})
.catch(function(error) {
alert(error.message);
});
}
我的navClicked()函数调用了哪个。此函数检查以查看用户当前位于哪个导航部分,并将所需信息返回到渲染部分:
navClicked(name) {
if(name === "signout"){
return(
<button className="btn btn-info" onClick={this.logOutUser()}>
Sign Outed
</button>
)
}
}
最后是我的渲染部分。我正在使用react-bootstrap卡,并查看在配置文件卡上单击了哪个导航。
render(){
const length = window.location.href.length;
const current = window.location.href.slice(30, length);
return(
<Card className = "cardosettings" style={{ width: '60rem', height: '35rem'}}>
<Card.Header className = 'header0'>
<Nav variant="tabs" defaultActiveKey="#profile">
<Nav.Item >
<Nav.Link className = 'linka' href="#profile">Edit Profile</Nav.Link>
</Nav.Item>
<Nav.Item>
<Nav.Link className = 'linka' href="#settings">Account Settings</Nav.Link>
</Nav.Item>
<Nav.Item>
<Nav.Link className = 'linka' href="#signout">Sign Out</Nav.Link>
</Nav.Item>
</Nav>
</Card.Header>
<ListGroup variant="flush">
{this.navClicked(current)}
</ListGroup>
</Card>
)
}
任何提示都将不胜感激!
答案 0 :(得分:3)
请尝试更改logoutUser和箭头回调函数,以避免与this
绑定问题:
logOutUser = () => {
var tempname = login.getUser();
firebase
.auth()
.signOut()
.then(() => {
alert("Goodbye " + tempname + "!");
this.props.history.push('/');
})
.catch(function(error) {
alert(error.message);
});
}
此外,如果您要处理的默认情况下可能未获得历史记录的子组件,请用withRouter
中的router-router-dom
包装组件。
import { withRouter } from 'react-router-dom';
export default withRouter(YourComponent);