[英]How do you conditionally render a React Native FlatList depending on the contents of the array?
I have an array completedTests
in my app, with one example of its contents being this (when I use console.log()
):我的应用程序中有一个数组
completedTests
,其内容的一个示例是这样的(当我使用console.log()
时):
Array [
Object {
"difference": 140,
"id": "Practice Test 3",
"targetReached": false,
"testScore": "1400",
}
]
To display its contents I would use:要显示其内容,我将使用:
<View>
<FlatList
data={completedTests}
keyExtractor={item => item.id}
renderItem={({ item }) => (
<View style={[styles.scoreOverview, { backgroundColor: '#596b96' }]}>
<Text>{item.id}</Text>
<Text>{item.testScore}</Text>
<Text>{item.targetReached.toString()}</Text>
<Text>{item.difference}</Text>
</View>
)} />
</View>
If the array is empty, I would set my array to be ["none"]
, and trying to display this causes the following error:如果数组为空,我会将数组设置为
["none"]
,并尝试显示它会导致以下错误:
undefined is not an object (evaluating 'item.targetReached.toString`)
undefined 不是 object(评估“item.targetReached.toString”)
How do I conditionally render my FlatList
in the way I want?如何以我想要的方式有条件地呈现我的
FlatList
?
Instead of setting your array to "none" use this approach不要将您的数组设置为“无”,而是使用这种方法
<FlatList
data={completedTests}
keyExtractor={item => item.id}
ListEmptyComponent={<Text>None</Text>}
renderItem={({ item }) => (
<View style={[styles.scoreOverview, { backgroundColor: '#596b96' }]}>
<Text>{item.id}</Text>
<Text>{item.testScore}</Text>
<Text>{item.targetReached.toString()}</Text>
<Text>{item.difference}</Text>
</View>
)} />
The ListEmptyComponent would render when the array you supply is empty当您提供的数组为空时, ListEmptyComponent将呈现
I think this might work in what you are trying to do there...我认为这可能适用于你在那里尝试做的事情......
<View>
{
completedTests[0] !== "none" ? (<FlatList
data={completedTests}
keyExtractor={item => item.id}
renderItem={({ item }) => (
<View style={[styles.scoreOverview, { backgroundColor: '#596b96' }]}>
<Text>{item.id}</Text>
<Text>{item.testScore}</Text>
<Text>{item.targetReached.toString()}</Text>
<Text>{item.difference}</Text>
</View>
)} />) : (
<Text>None</Text>
)
}
</View>
so you check the array content and if it's not the ["none"]
then you can render flatList else something else or nothing.所以你检查数组内容,如果它不是
["none"]
那么你可以渲染 flatList 其他东西或什么都没有。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.