簡體   English   中英

在 React Native 中映射嵌套的對象數組

[英]Mapping a nested array of objects in React Native

我正在嘗試根據其對象之一顯示具有變化的項目列表。 請參閱下面的代碼以獲取一些見解:

 data: [{ "transportation": [ {"id": "1", "name": "bus", "type": "large"}, {"id": "2", "name": "bicycle", "type": "small"}], "animal": [ {"id": "3", "name": "elephant", "type": "large"}, {"id": "4", "name": "mouse", "type": "small"}] }]

對於上面的示例,如果類型為“大”,我想顯示一些簡單的內容,例如“大”文本,如果類型為“小”,則顯示“小”文本。我想到的第一件事是進行嵌套地圖(數據的外部地圖,運輸/動物的內部地圖)。我首先在沒有外部地圖的情況下測試內部地圖,如下圖所示:

 data.animal.map((info) => { switch (info.type){ case "large": return( <View> <Text>Large</Text> </View>); case "small": return( <View> <Text>Small</Text> </View>); default: return( <View> <Text>Whatever</Text> </View>); } })

我有

類型錯誤:無法讀取未定義的屬性“地圖”

知道為什么會發生這種情況嗎?

編輯:

我曾嘗試在等待答案時進行嵌套循環。 下面是我的代碼片段:

 data.map((category, key) => { return( Object.keys(category).map((info) => { switch (info.type){ case "large": return( <View> <Text>Large</Text> </View>); case "small": return( <View> <Text>Small</Text> </View>); default: return( <View> <Text>Whatever</Text> </View>); } }) ) })

它運行沒有錯誤,但它沒有給我預期的結果。 所有輸出都切換到默認值,即“隨便”。

您正在訪問數據數組的第一個對象。 所以你的代碼應該是

data[0].animal.map((info) => {
....

 data = [{ "transportation": [ {"id": "1", "name": "bus", "type": "large"}, {"id": "2", "name": "bicycle", "type": "small"}], "animal": [ {"id": "3", "name": "elephant", "type": "large"}, {"id": "4", "name": "mouse", "type": "small"}] }] data[0].animal.map((info) => { return console.log(info) } )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM