首页 > 解决方案 > 在 react-native 中使用 FlatList 时数据未呈现

问题描述

我正在尝试使用 flatlist 呈现在屏幕上输入的数据,以便滚动选项适用于我的应用程序。没有显示错误,但数据未呈现。

这是我的代码:

import React, { useState } from 'react';
import { StyleSheet, Text, View, Button, TextInput, ScrollView, FlatList } from 'react-native';

export default function App() {
    const [enteredGoal, setEnteredGoal] = useState('');
    const [courseGoals, setCourseGoals] = useState([]);
    const goalInputHandler = (enteredText) => {
        setEnteredGoal(enteredText);
    };
    const addGoalHandler = () => {
        setCourseGoals(currentGoals => [...courseGoals, { id: Math.random().toString(), value: enteredGoal }]);
    };

    return (
        <View style={styles.screen}>
            <View style={styles.inputContainer}>
                <TextInput placeholder="Course Goal"
                    style={styles.input}
                    onChangeText={goalInputHandler}
                    value={enteredGoal} />
                <Button title="Add" onPress={addGoalHandler} />
            </View>
            <FlatList
                keyExtractor={(item, index) => item.id}
                data={courseGoals} renderItem={itemData => {
                    courseGoals.map((goal) =>
                        <View style={styles.listItem}><Text>{itemData.item.value}</Text></View>)
                }} />

        </View>

    );
}

const styles = StyleSheet.create({
    screen: {
        padding: 50
    },
    inputContainer: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center' },
    input: {
        width: '80%', borderColor: 'black', borderWidth: 1, padding: 10
    }
    , listItem: {
        padding: 10,
        margin: 10,
        backgroundColor: '#ccc',
        borderColor: 'black',
        borderWidth: 1
    }
});

你能帮帮我吗?

标签: react-nativereact-native-flatlist

解决方案


我认为该项目没有正确返回,renderItem并且您不需要迭代courseGoals它,因为它已经绑定到data.

尝试将您的更新renderItem为:

renderItem={itemData => (
  <View style={styles.listItem}><Text>{itemData.item.value}</Text></View>
)}

推荐阅读