简体   繁体   中英

Get Error 'Cannot read property 'setState' of undefined' on setState line

I keep getting this error for some reason and i dont understand why, the error is

在此处输入图像描述

Here is the relevent bit of the code below, i am passing two objects as props into this DashBoard component, one is a firebase user object and the other is a database object that i use to retrieve some data from firebase, I checked and the two objects are imported properly(as shown by the commented console logs), but i keep getting this error and i dont know why?

import React from 'react';


export default class Dashboard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {dataArray: []};
  }

  async componentDidMount() {
    console.log("i am inside dashboard");
    //console.log(this.props.user);
    //console.log(this.props.database);

    let database = this.props.database;

    const docRef = database.collection("Some_Collection_here").doc("Some_Id_here")
    let dataRetrieved = null;

    docRef.get().then(function(doc) {
      if (doc.exists) {
        const dataRetrieved = doc.data();
        this.setState ({dataArray: dataRetrieved});
      } else {
        console.log("Error: no such document exists");
      }
    })
  }

  render() {
    return (
      <div>

      </div>
    );
  }
}

I get your question. I think this will be ok.

import React from 'react';


export default class Dashboard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {dataArray: []};
  }

  async componentDidMount() {
    console.log("i am inside dashboard");
    //console.log(this.props.user);
    //console.log(this.props.database);

    let database = this.props.database;

    const docRef = database.collection("Some_Collection_here").doc("Some_Id_here")
    let dataRetrieved = null;

    docRef.get().then(doc => {
      if (doc.exists) {
        const dataRetrieved = doc.data();
        this.setState ({dataArray: dataRetrieved});
      } else {
        console.log("Error: no such document exists");
      }
    })
  }

  render() {
    return (
      <div>

      </div>
    );
  }
}

The reason is:

  1. This context
  2. Lexical scope

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM