javascript - componentDidMount() 中的 "This is undefined"错误

标签 javascript node.js reactjs ecmascript-6

当我在我的 componentDidMount 方法中使用它时,我得到一个 TypeError: this is undefined,即使我相信我绑定(bind)了该方法。我是否错误地绑定(bind)了方法或者是否存在其他问题?我尝试同时使用箭头函数并将其绑定(bind)到构造函数中,但我遇到了同样的错误。


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

最佳答案

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

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

默认情况下 React 的生命周期钩子(Hook)像 componentDidMount 已经有这个上下文。所以你需要把你的代码改成这个。

componentDidMount() {

}

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

关于javascript - componentDidMount() 中的 "This is undefined"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56160541/

相关文章:

javascript - 用星号替换数字 javascript/jquery?

javascript - 使用 Drag 属性时,如何让 React Framer-motion 为移动设备触发 onClick 事件?

javascript - 无法将 Node docker容器连接到mongo docker容器

javascript - 使用 grunt-exec 和 powershell 执行 linkchecker.exe

javascript - Node/异步 : how to keep my code easy to understand

reactjs - Next.JS 静态生成在使用 `map` 方法时不是 SEO 的最佳选择

javascript - 不同功能的 Mocha 测试用例

javascript - 如何在 Internet Explorer 中支持 Chrome 文件导出功能?

javascript - 当存在未缓存的 javascript src 文件时,浏览器会做什么?

Javascript三.js平滑相机运动