【问题标题】:How do you conditionally render a React Native FlatList depending on the contents of the array?如何根据数组的内容有条件地渲染 React Native FlatList?
【发布时间】:2021-05-17 04:36:37
【问题描述】:

我的应用中有一个数组 completedTests,其中一个内容示例如下(当我使用 console.log() 时):

Array [
  Object {
    "difference": 140,
    "id": "Practice Test 3",
    "targetReached": false,
    "testScore": "1400",
  }
]

为了显示它的内容,我会使用:

<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>

如果数组为空,我会将我的数组设置为["none"],并尝试显示它会导致以下错误:

undefined 不是一个对象(评估 'item.targetReached.toString`)

如何以我想要的方式有条件地渲染我的FlatList

【问题讨论】:

  • 为什么没有空数组?
  • completedTests 从 Firebase Firestore 获取数据,因此对于新用户来说它将是空的
  • 这里的问题是你有一个字符串“none”类型的项目,唯一的选择是检查类型并决定组件
  • 我该怎么做?
  • 请参考我的回答

标签: javascript react-native react-native-flatlist


【解决方案1】:

不要将您的数组设置为“无”,而是使用这种方法

<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>
         )} />

ListEmptyComponent 将在您提供的数组为空时呈现

【讨论】:

    【解决方案2】:

    我认为这可能适用于你在那里尝试做的事情......

           <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>
    

    所以你检查数组内容,如果不是["none"],那么你可以渲染 flatList 其他东西或什么都没有。

    【讨论】:

    • 这确实可以在我想要的位置显示“无”,但由于某种原因,它会完全冻结我的应用程序并使其无响应,除非我重新加载它。知道为什么吗?
    • 您的控制台中是否有任何错误或警告? @KLG
    • 没有任何错误或警告,整个应用程序只是不响应我在屏幕上触摸的任何内容。
    • 然后改变你的方法,就像@Guruparan 说的那样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 2019-04-06
    • 1970-01-01
    相关资源
    最近更新 更多