Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript &引用;这是未定义的;componentDidMount()中出错_Javascript_Node.js_Reactjs_Ecmascript 6 - Fatal编程技术网

Javascript &引用;这是未定义的;componentDidMount()中出错

Javascript &引用;这是未定义的;componentDidMount()中出错,javascript,node.js,reactjs,ecmascript-6,Javascript,Node.js,Reactjs,Ecmascript 6,我得到一个a类型错误:当我在componentDidMount方法中使用它时,这是未定义的,尽管我相信我绑定了该方法。我是否绑定了错误的方法,或者是否存在其他问题?我尝试使用这两个箭头函数并将其绑定到构造函数中,但得到了相同的错误 constructor(...args) { super(...args); // this.handleSubmit = this.handleSubmit.bind(this); this.state = { email:

我得到一个a类型错误:当我在componentDidMount方法中使用它时,这是未定义的,尽管我相信我绑定了该方法。我是否绑定了错误的方法,或者是否存在其他问题?我尝试使用这两个箭头函数并将其绑定到构造函数中,但得到了相同的错误


  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 (...)}}```

我认为您做错了,因为您在组件didmount(React的生命周期钩子方法)中使用了arrow函数。因此,您不再需要这些代码行了

 this.componentDidMount = this.componentDidMount.bind(this); // remove this one
默认情况下,React-like componentDidMount的生命周期钩子已经具有此上下文。所以你需要把你的代码改成这个

componentDidMount() {

}
因此,要清楚,如果您使用的是箭头函数,则无需使用bind(此)


如果您不熟悉javascript中的
这个
,只需到处使用arrow函数。

您不需要绑定生命周期方法。从构造函数中删除这一行就可以了。this.componentDidMount=this.componentDidMount.bind(this);
componentDidMount() {
    firebaseRef.auth().onAuthStateChanged(user => {
        // your code
    })
}