首页 > 解决方案 > 反应路由器重定向 - 无法读取未定义的属性“道具”

问题描述

谁能帮我理解这里出了什么问题?

我试图在注销后重定向到登录页面。

这是代码

import React, { Component } from "react";
import firebase from "../Firebase/firebase";
import { withRouter, Redirect } from "react-router-dom";

class Home extends Component {
  constructor(props) {
    super(props);
    this.logout = this.logout.bind(this);
  }

  state = {};

  logout = e => {
    e.preventDefault();
    firebase
      .auth()
      .signOut()
      .then(
        function() {
          console.log("Signed Out");
          this.props.history.push("/login");
        },
        function(error) {
          console.error("Sign Out Error", error);
        }
      );
  };

  render() {
    return (
      <div align="center" className="container">
        <h1> Home page </h1>
        <br />
        <br />
        <h2>Hello: {this.state.user} </h2>
        <button
          className="btn btn-lg text-white"
          style={{ backgroundColor: "#B65DF3" }}
          onClick={this.logout}
        >
          Logout
        </button>
      </div>
    );
  }
}

export default withRouter(Home);

这是错误消息

TypeError:无法读取未定义的属性“道具”

我不明白为什么它不起作用,因为我在此处重定向的登录页面完全相同并且有效。

标签: reactjsreact-router

解决方案


您的问题将是您传递的匿名函数.then。尝试用粗箭头或类似的东西替换它:

  logout = (e) => {
        e.preventDefault();
        firebase.auth().signOut().then(this.handleResolve).catch(this.handleError)
    }

  handleResolve = () => {
    console.log('Signed Out');
    this.props.history.push('/login')
  }

  handleError = (error) => {
    console.error('Sign Out Error', error);
  }

推荐阅读