首页 > 解决方案 > Firebase Auth Signout 未推送到 React Web 应用程序中的主页

问题描述

我有一个“退出”按钮,它在提交时显然会删除用户会话。

单击按钮时令牌会被删除,然后我希望它在成功删除令牌后重定向到主页。但是,单击按钮时会出现以下错误:

未处理的承诺拒绝:TypeError:未定义不是对象(评估“this.props”)

我不明白为什么会这样,因为代码原则上类似于调用“this.props.history.push”的其他函数。

这是我的组件:

class ProfileBox extends Component {
  constructor(props) {
    super(props)

  }

  async signOut(e) {

    e.preventDefault()

    await firebase.auth().signOut().then(function() {
      console.log("Successfully signed out.")

    }).catch(function(error) {
      console.log(error)
      console.log("An error occurred")
    });

    this.props.history.push("/");
  }

  render() {
    return (

          <button className="profile-box-logout" type="submit" name="button" onClick={this.signOut}>Logout</button>

    )
  }

}

谁能指出我做错了什么?

标签: javascriptreactjsfirebasefirebase-authentication

解决方案


这个问题与 Firebase 没有任何关系。this在该函数中为 null ,这就是抛出错误。如果您在渲染中移动该函数,那么它将起作用。尝试这样的事情:

render() {

    const signOut = async (e) => {
      e.preventDefault();

      await firebase.auth().signOut().then(function() {
        console.log("Successfully signed out.")

      }).catch(function(error) {
        console.log(error)
        console.log("An error occurred")
      });

      this.props.history.push("/");
    }
    
    return (
      <button
        className="profile-box-logout"
        type="submit"
        name="button"
        onClick={signOut}
      >
        Logout
      </button>
    );
  }

这将使您可以访问this.props. 工作示例:https ://codesandbox.io/s/a-simple-react-router-v4tutorial-forked-sbrnd?file=/components/Schedule.js


推荐阅读