【发布时间】:2021-06-09 12:03:40
【问题描述】:
我试图从这个只读示例 JSON 中返回第一个水果/颜色数据:
"start": 0,
"limit": 1,
"filteredSize": null,
"results": [
{
"id": 20587193,
"fruit": "apple",
"color": "red",
},
{
"id": 20587191,
"fruit": "banana",
"color": "yellow",
}
]
在 React Native 中使用 FlatList:
<FlatList
data={data.results}
keyExtractor={({ id }, index) => id.toString()}
renderItem={({ item }) => (
<exampleComponent
fruitData={item.fruit}
colourData={item.color} />
)}
/>
这是我的 API 调用:
fetch('http://localhost:8080/login', headers)
.then((response) => response.json())
.then((json) => setData(json))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
然而,上面返回的结果是水果和颜色:
apple, red
banana, yellow
我知道我需要访问data.results 的第一个元素的索引,但我不确定将其放在我的代码中的哪个位置。
如果我将data.results 的console.log 添加为链式.then,如下所示:
fetch('http://localhost:8080/login', headers)
.then((response) => response.json())
.then((json) => setData(json))
.catch((error) => console.error(error))
.then(function(){
console.log("dataResults: " + data.results)
})
.finally(() => setLoading(false));
}, []);
由于某种原因,它调用了 3 次,但第一次未定义,所以也许这就是我遇到麻烦的原因:
console.log output:
dataResults: undefined
dataResults: [object Object],[object Object]
dataResults: [object Object],[object Object]
我的许多尝试都返回TypeError: Cannot read property '0' of undefined 错误,例如将console.log 调用更改为:
console.log("dataResults: " + data.results[0])
更新
我现在知道console.log 被多次调用是因为useEffect 被重新渲染,而不是useEffect 本身被多次调用。
但是我还是不明白为什么我不能访问data.results进行过滤,却可以访问data.results整体使用?
如何在我的 FlatList 中使用 data 数组之前对其进行编辑?
【问题讨论】:
标签: json react-native-flatlist