2016-09-06 60 views
1

我试图通过props将一些Firebase数据从一个组件传递到另一个组件,但似乎并没有让我遍历子组件中的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数据才能在映射之前解决,如果是的话,我该如何执行此操作?

任何帮助表示赞赏。提前致谢!

回答

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}); 
} 

这将导致应用程序组件的重新渲染,造成了新的数据作为道具的游戏组件传递。

+1

感谢您的支持!我不得不把'this.setState()'行放在firebase回调中。这似乎工作! – realph