2017-08-02 19 views
0

所以我有一個像這樣一個對象,如何循環訪問數組的對象在原生答案中創建視圖?

Object{ 2017-08-01:Array(2), 2017-08-02:Array(1) } 

我用下面的代碼,來遍歷它,

return Object.keys(this.state.visits).map(function(key, index){ 
      console.log(key); 
      return (
       <View style={{height: 40, flexDirection: 'row'}}> 
        <Text style={{marginLeft: 10,marginTop: 10, fontWeight:'500'}}>{key}</Text> 
       </View> 
      ); 
     }); 

發生的是,這段代碼,打印出的「鑰匙」完美地console.log,但在視圖中,只有最後一個日期被打印,並且我也在控制檯中出現錯誤,例如

警告:數組或迭代器中的每個子都應該有一個唯一的「密鑰「 道具。

檢查渲染方法filename。有關更多信息,請參閱 https://facebook.github.io/react/docs/lists-and-keys.html#keys

我試圖做到的,是如下,

+-------------------------------------------------------------+ 
|       Date1        | 
+-------------------------------------------------------------+ 
|       Record 1       | 
+-------------------------------------------------------------+ 
|       Record 2       | 
+-------------------------------------------------------------+ 


+-------------------------------------------------------------+ 
|       Date 2       | 
+-------------------------------------------------------------+ 
|       Record 1       | 
+-------------------------------------------------------------+ 

但我被困在日期部分,所以我不能夠繼續進行。

回答

1

我建議你看看https://facebook.github.io/react-native/docs/sectionlist.html,這很適合你對基於段的數據集的需求。

<SectionList 
    renderItem={({item}) => <ListItem title={item.title} />} // Your record component here. 
    renderSectionHeader={({section}) => <H1 title={section.title} />} // Your date component here. 
    sections={[ // homogenous rendering between sections 
    {data: [...], title: ...}, 
    {data: [...], title: ...}, 
    {data: [...], title: ...}, 
    ]} 
/> 

上面的工作很好,如果您的部分中的列表行非常相似。您也可以通過傳遞在每節的renderItem方法對不同部分的不同組件:

<SectionList 
    sections={[ // heterogeneous rendering between sections 
    {data: [...], title: ..., renderItem: ...}, 
    {data: [...], title: ..., renderItem: ...}, 
    {data: [...], title: ..., renderItem: ...}, 
    ]} 
/> 

此外,警告有關Each child in an array or iterator should have a unique "key" prop.是因爲你基本上是回類似的數據陣列,並作出反應要你傳遞一個key的道具,以幫助它更好地識別渲染和重新渲染時的組件。您應該通過一個key道具作爲您的重複組件的根源,如下所示<View style={{ height: 40, flexDirection: 'row' }} key={key}>

1

您應該爲<View />中的道具「鑰匙」賦予唯一的值。

return Object.keys(this.state.visits).map(function(key, index){ 
      return (
       // Key prop 
       <View key={key}> 
        <Text style={{marginLeft: 10,marginTop: 10, fontWeight:'500'}}>{key}</Text> 
        {func_record()} // return map for records 
       </View> 
      ); 
     }); 
... 
render() { 
    return (<View style={{ flex: 1 }}> 
     {your_func_name()} 
    </View>); 
}