【问题标题】:Cant access object passed to component React无法访问传递给组件 React 的对象
【发布时间】:2019-08-02 13:40:03
【问题描述】:

我想将一个对象传递给一个 React 组件。该对象是父元素的状态,它会随着来自 firebase 的更新而动态更新。但是,当我将此对象传递给组件并尝试访问其值时,我得到了未定义。

当我尝试在控制台中记录此对象时,它会显示带有Value below was just evaluated now 的键值对。如何访问该对象的属性?

父母的状态

state = {
    isSignedIn: false,
    userVal: {},
    cards: {},
    coin: 0,
    room_id: 0
  };

对象正在更新

db.collection("users").doc(this.state.userVal.uid).onSnapshot(query => {
        let q = query.data();
        this.setState({ room_id: q.room_id, coin: q.coins });
        for (const key in q) {
          if (key !== "room_id" && key !== "name" && key !== "coins" && key !== "email" && key !== "no") {
            let temp = this.state.cards;
            temp[key] = q[key];
            this.setState({ cards: temp });
          }
        }
      })

对象传递给组件

<Cards id={this.state.userVal.uid} room_id={this.state.room_id} cards={this.state.cards} />

this.state.cards 是有问题的

【问题讨论】:

  • 如果您向我们展示您的一些代码将会很有用。
  • 可能是因为获取firebase是异步函数。
  • 首先不要在循环中使用 set State 不是一个好方法
  • 如果有效,请接受答案。
  • @BillF,你可能是对的

标签: javascript reactjs firebase


【解决方案1】:

这是因为 this 的范围是未定义的。您需要使用 ES6 箭头函数传递它。

  db.collection("users").doc(this.state.userVal.uid).onSnapshot(query => {
    let q = query.data();
    this.setState({ room_id: q.room_id, coin: q.coins });
    q.forEach((key) => {
      if (key !== "room_id" && key !== "name" && key !== "coins" && key !== "email" && key !== "no") {
        let temp = this.state.cards;
        temp[key] = q[key];
        this.setState({ cards: temp });
      }
    })
  })

试试这个方法。

【讨论】:

  • 我找到了一个不涉及向组件发送对象的解决方法。但是这不起作用
猜你喜欢
  • 1970-01-01
  • 2018-04-14
  • 1970-01-01
  • 2020-11-28
  • 2020-12-21
  • 1970-01-01
  • 2018-11-27
  • 1970-01-01
  • 2017-06-18
相关资源
最近更新 更多