【问题标题】:"This is undefined" error in componentDidMount()componentDidMount() 中的“这是未定义”错误
【发布时间】:2019-10-03 06:12:47
【问题描述】:

当我在 componentDidMount 方法中使用 this 时,我得到一个 TypeError: this is undefined,即使我相信我绑定了该方法。是我错误地绑定了方法还是有其他问题?我尝试使用这两个箭头函数并将其绑定在构造函数中,但我得到了同样的错误。


  constructor(...args) {
    super(...args);
    // this.handleSubmit = this.handleSubmit.bind(this);
    this.state = {
      email: null,
      address: null,
      address2: null,
      city: null,
      state: null,
      zip: null,
      subscribe: null,
      currentUser: null,
      displayName: null,
      uid: null,
    }
    this.handleChange = this.handleChange.bind(this);
    this.componentDidMount = this.componentDidMount.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);


  }
  componentDidMount = () => {
    firebaseRef.auth().onAuthStateChanged(function(user) {

      if (user) {
        [...]
        })
        this.setState({
          uid: user.uid,
          displayName: user.displayName});

        db.collection("testCollection").doc("handleSubmitTest8").set({
          // uid:this.state.uid,
          test: "testy",

        }).then(function() {
          console.log("Document written in handleSumit in NUM");

        })
        .catch(function(error) {
          console.error("Error adding document: ", error);
        });

      } else {
        console.log("no user signed in");
      }

    });
  }

  handleSubmit = (event) => {
    [...]
  }

  handleChange(event) {
   [...]

  }
  render() {
    return (...)}}```

【问题讨论】:

  • 你不需要绑定生命周期方法
  • 从构造函数中删除这一行,你就可以开始了。 this.componentDidMount = this.componentDidMount.bind(this);

标签: javascript node.js reactjs ecmascript-6


【解决方案1】:

我认为您做错了,因为您在 componentDidMount 中使用了箭头函数( React 的生命周期挂钩方法)。所以你不再需要这行代码了

 this.componentDidMount = this.componentDidMount.bind(this); // remove this one

默认情况下,像 componentDidMount 这样的 React 生命周期钩子已经有了这个上下文。因此,您需要将代码更改为此。

componentDidMount() {

}

所以要清楚,如果你使用箭头函数,不需要使用 bind(this)

【讨论】:

    【解决方案2】:
    componentDidMount() {
        firebaseRef.auth().onAuthStateChanged(user => {
            // your code
        })
    }
    

    如果您不熟悉 javascript 中的 this,请在任何地方使用箭头函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-19
      • 2019-12-18
      • 2019-07-11
      • 2023-01-20
      • 2017-02-06
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多