无法将访问对象传递给组件React

时间:2019-03-12 06:34:32

标签: javascript reactjs firebase

enter image description here

我想将对象传递给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是有问题的

1 个答案:

答案 0 :(得分:1)

这是因为此操作的范围未定义。您需要使用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 });
      }
    })
  })

尝试一下。