从Firestore获取数据后如何设置状态

埃里克

我目前可以从Firestore中获取用户数据,但是在保存用户文档数据时遇到了麻烦。我的控制台下面出现错误

  TypeError: this.setState is not a function
    at Object.next (RepRequest.js:32)
    at index.cjs.js:1344
    at index.cjs.js:1464

我试图从Ca n't setState Firestore data跟踪另一个用户的问题,但是仍然没有成功。

获取数据后,我确实有两个api请求,然后便可以设置状态。我尝试将Firestore请求合并到promise.all中,但无法成功,这就是我将其分离的原因。也许我走错了路,任何指导都值得赞赏。

import React, { useEffect, useState } from "react";
import app from "./config/base.js";
import axios from "axios";

export default class RepRequest extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userInfo: [],
      fedSens: [],
      fedReps: []
    };
  }

  componentDidMount() {
    const items = [];
    app.auth().onAuthStateChanged(function(user) {
      if (user) {
        console.log("User is signed in");
        let db = app
          .firestore()
          .collection("user")
          .doc(user.uid);
        db.get().then(doc => {
          if (doc.exists) {
            console.log("Document data:", doc.data());
            items.push(doc.data());
          } else {
            console.log("No doc exists");
          }
        });
      }
      this.setState({ userInfo: items });
    });

    Promise.all([
      axios.get(
        `https://api.propublica.org/congress/v1/116/senate/members.json`,
        {
          headers: { "X-API-Key": "9wGKmWl3kNiiSqesJf74uGl0PtStbcP2mEzSvjxv" }
        }
      ),
      axios.get(
        `https://api.propublica.org/congress/v1/116/house/members.json`,
        {
          headers: { "X-API-Key": "9wGKmWl3kNiiSqesJf74uGl0PtStbcP2mEzSvjxv" }
        }
      )
    ]).then(([rest1, rest2]) => {
      this.setState({
        fedSens: rest1,
        fedReps: rest2
      });
    });
  }

  render() {
    if (this.state.fedReps.length <= 0)
      return (
        <div>
          <span>Loading...</span>
        </div>
      );
    else {
      console.log(this.state.fedReps);
      return <div>test</div>;
    }
  }
}
samthecodingman

您的问题来自混合lambda函数声明((...) => { ... })和传统函数声明(function (...) { })。

Lambda函数将从this定义的地方继承,但传统函数this将与定义的地方隔离。这就是为什么var self = this;在旧版兼容代码中常见的原因,因为this通常与您想要的不匹配。

这是演示此行为的示例片段:

function doSomething() {
  var anon = function () {
    console.log(this); // 'this' is independent of doSomething()
  }
  
  var lambda = () => {
    console.log(this); // inherits doSomething's 'this'
  }

  lambda(); // logs the string "hello"
  anon(); // logs the 'window' object
}

doSomething.call('hello')

因此,您有两种可用的方法。使用您喜欢的任何一种。

选项1:使用Lambda表达式

app.auth().onAuthStateChanged(function(user) {

app.auth().onAuthStateChanged((user) => {

选项2:分配“自我”变量

const items = [];
app.auth().onAuthStateChanged(function(user) {
  // ...
  this.setState({ userInfo: items });
}

const items = [];
const component = this; // using "component" makes more sense than "self" in this context
app.auth().onAuthStateChanged(function(user) {
  // ...
  component.setState({ userInfo: items });
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章