2016-09-06 23 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