2016-04-10 39 views
0

我在firebase中有一些記錄,這段代碼是將其取出並將結果放到子組件中。這裏的代碼ReactJS - 如何獲得Firebase結果並正確傳遞到子組件

import React from "react"; 

export default class Home extends React.Component{ 
    componentWillMount(){ 
     this.firebaseRef = new Firebase('https://sweltering-heat-7923.firebaseio.com/contact'); 
     this.firebaseRef.once("value", function (snapshot){ 
      snapshot.forEach(function(data){ 
       console.log(data.val()); 
      }); 
     }); 
    } 
    render(){ 
     return(
      <List /> 
     ) 
    } 
} 

class List extends React.Component{ 
    render(){ 
     return(
      <div class="row"> 
       // populate props from Home component 
      </div> 
     ) 
    } 
} 

我不怎麼做的是將響應數據傳遞給在這種情況下是List的子組件。

而且火力點的數據是這樣的:

object { 
    id:12131323, 
    firstName:'john', 
    address: {steet:'some street', city:'havana'} 
} 
object { 
    id:12221232, 
    firstName:'joe', 
    address:{steet:'big street', city:'dubai'} 
} 

回答

3

我認爲你在尋找用於填充一些物品清單。你的代碼的 稍作修改:

class Home extends React.Component{ 


constructor(props) { 
super(props); 
    this.state = { 
    items: [], 
    } 
/// must set initial state, because this is being passed as a prop 
} 
componentWillMount(){ 

    const self = this; 
    const url = 'https://sweltering-heat-7923.firebaseio.com/contact'; 
    this.firebaseRef = new Firebase(url); 
    this.firebaseRef.once("value", function (snapshot){ 

// update state with new items 
// which will cause re-rendering of <List> with the new items. 
     snapshot.forEach(function(data){ 
      self.setState({ 
       items: self.state.items.concat(data.val()) 
      }) 

     }); 
    }); 


} 
render(){ 
    return(
     <List items = { this.state.items } /> 
    ) 
    } 
} 

和列表將是這個樣子:

const List = (props) => { 


    return (
     <ul> 
     { props.items.map((item,i) => { 

     const { firstName, id } = item; 
     const address = item.address.street + ', ' + item.address.city; 

     return (

     <li key = { i } > 
     <div>{ id }</div> 
     <div> { name } </div> 
     <div> { address} </div> 
     </li> 
     ) 


     })} 
     </ul> 
    ) 
} 

這裏所發生的是:

1)設定應用程序的初始狀態空數組稱爲items

2)通過將新項目添加到items陣列來更新狀態

3)items陣列傳遞到列表組件,作爲值的道具稱爲items<List items = { items } />

4)在丙items的值映射來呈現實際的項目。

希望這會有所幫助!

相關問題