React:通过道具传递Firebase数据

时间:2016-09-06 00:26:26

标签: javascript reactjs firebase firebase-realtime-database

我试图将一些Firebase数据从一个组件通过props传递到另一个组件,但它似乎不允许我迭代子组件中的Firebase数据。

App.js

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      games: []
    };
  }

  componentDidMount() {
    const gamesRef = firebase.database().ref('games').orderByKey();

    gamesRef.once('value', snap => {
      snap.forEach((childSnapshot) => {
        this.state.games.push(childSnapshot.val());
      })
    })
  }

  render() {
    return (
      <div className="App">
        <Games data={ this.state.games } />
      </div>
    );
  }
}

Games.js

class Games extends Component {
  componentDidMount() {
    console.log(this.props.data); // this logs successfully  
  }

  render() {
    return (
      <div className="container">
        <div className="Games flex flex-end flex-wrap">
          { this.props.data.map(function (game, i) {            
            return (
              <h1>{ game.title }</h1>
            )
          }) }
        </div>

      </div>
    );
  }
}

由于某些原因,我在map()尝试props.data时出现问题。它肯定会传递给我的Games组件,因为它会使用从Firebase返回的数据将console.log(this.props.data)打印到控制台。

在映射之前是否必须等待我的Firebase数据解析,如果是,我该怎么做?

感谢任何帮助。提前谢谢!

1 个答案:

答案 0 :(得分:1)

我认为问题在于您的App类中的componentDidMount。你正在用

更新状态
this.state.games.push(childSnapshot.val());

你不应该这样做。只应使用this.setState更新状态(或者至少应该使用this.forceUpdate()),否则它将不会重新呈现。我会建议做

componentDidMount() {
  const gamesRef = firebase.database().ref('games').orderByKey();
  let newGames;

  gamesRef.once('value', snap => {
    snap.forEach((childSnapshot) => {
      newGames.push(childSnapshot.val());
    })
  })

  this.setState({games: newGames});
}

这会导致重新呈现App组件,导致新数据作为prop传递给Games组件。