【问题标题】:React: Pass Firebase Data Down Via PropsReact:通过道具传递 Firebase 数据
【发布时间】:2016-09-06 00:26:25
【问题描述】:

我正在尝试通过props 将一些 Firebase 数据从一个组件向下传递到另一个组件,但它似乎不允许我遍历子组件中的 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>
    );
  }
}

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

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

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

【问题讨论】:

    标签: javascript reactjs firebase firebase-realtime-database


    【解决方案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 组件重新渲染,从而将新数据作为道具传递给 Games 组件。

    【讨论】:

    • 谢谢!我最终不得不将this.setState() 行放在firebase 回调中。这似乎有效!
    猜你喜欢
    • 2019-08-09
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 2018-12-17
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    相关资源
    最近更新 更多