【问题标题】:Object appears to be undefined after this.setState在 this.setState 之后对象似乎未定义
【发布时间】:2020-05-12 11:57:30
【问题描述】:

我环顾四周,似乎找不到解决方案。非常感谢我能在这里得到的任何帮助.. 代码显然还有更多内容,但我相信我的错误就在这里的某个地方.. 我希望我的 allFirebaseItems 尽快成为一个完整且可用的对象,但我不知道完成它的方法。我很乐意提供所需的任何其他信息。

constructor(props) {
    super(props);

    this.state = {
      allFirebaseItems: {},
    };
  }

componentDidMount() {
    this.firebaseFetch();
  }

//to get the items from firebase
firebaseFetch = () => {
    const temp = {};
    database.ref(authentification.currentUser.uid).on("value", (snapshot) => {
      snapshot.forEach((category) => {
        category.forEach((date) => {
          if (!temp[date.key]) {
            temp[date.key] = [];
          }
          date.forEach((itemKey) => {
            var valuesToPush = {};
            itemKey.forEach((element) => {
              valuesToPush[element.key] = element.val();
            });
            temp[date.key].push(valuesToPush);
          });
        });
      });

      //gives me the object with the fetched information, works so far
      console.log(JSON.stringify(temp));

      //allFirebaseItems is still undefined and I don't know how to fix it
      this.setState(
        {allFirebaseItems: temp},
      );

    });
  };

【问题讨论】:

  • 你应该在database.ref的回调中使用setState
  • 您如何检查或确认您的状态对象不是最新的?不要忘记setState 是异步的。如果您在渲染函数中阅读this.state.allFirebaseItems,那里是空的吗?那看起来像什么?

标签: javascript reactjs react-native firebase-realtime-database


【解决方案1】:

setState() 并不总是立即更新组件。它可能会批量更新或将更新推迟到以后。这使得在调用 setState() 之后立即读取 this.state 是一个潜在的陷阱。相反,请使用 componentDidUpdate 或 setState 回调 (setState(updater, callback)),它们都保证在应用更新后触发。

在 setState 之后你不能得到一个 immudiate 值,因为它是异步的。如果需要,使用回调。

【讨论】:

    猜你喜欢
    • 2018-04-03
    • 1970-01-01
    • 2017-01-05
    • 2022-08-20
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多