使用 this.props.history.push('/') 的用户注销重定向不会重定向到所需页面

Jsc*_*mer 2 firebase reactjs

用户注销后,我希望页面导航回我的主屏幕,'/'. 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);
  });
}
Run Code Online (Sandbox Code Playgroud)

这是由我的 navClicked() 函数调用的。此函数检查用户当前所在的导航部分,并将所需信息返回到渲染部分:

navClicked(name) {
     if(name === "signout"){
       return(
         <button className="btn btn-info" onClick={this.logOutUser()}>
           Sign Outed
         </button>
       )
     }
 }
Run Code Online (Sandbox Code Playgroud)

最后这是我的渲染部分。我正在使用 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>
        )
    }
Run Code Online (Sandbox Code Playgroud)

非常感谢任何提示!

Gre*_*zik 5

尝试将 logoutUser 和您的回调更改为箭头函数以避免绑定问题this

logOutUser = () => {
  var tempname = login.getUser();
  firebase
  .auth()
  .signOut()
  .then(() => {
    alert("Goodbye " + tempname + "!");
    this.props.history.push('/');
  })
  .catch(function(error) {
    alert(error.message);
  });
}

Run Code Online (Sandbox Code Playgroud)

此外,如果您正在处理默认情况下可能无法访问历史记录的子组件,请使用withRouterfrom包装您的组件router-router-dom

import { withRouter } from 'react-router-dom';
export default withRouter(YourComponent);
Run Code Online (Sandbox Code Playgroud)