FlatList renderItem 返回未定义

时间:2021-02-10 23:43:42

标签: react-native react-native-flatlist

我有一个 flatList 来渲染一个带有一些道具的组件,但是 renderItem 返回我“未定义”。我是本机反应的新手,我找不到解决方案。谢谢

编辑:

我在“posts.js”中使用的样式是否有可能影响 flatList 渲染?

Feed.js:

  export default function Feed() {
    const Posts = [
        { id: 1, title: "eu", photoDesc: 'eu' },
        { id: 2, title: "me", photoDesc: 'me' }

    ]
    console.log;

    return (
        <FlatList
            keyExtractor={props => props.id}
            data={Posts}
            renderItem={({ item }) => <FeedPosts title={`${item.title}`} photoDesc={`${item.photoDesc}`} ></FeedPosts>}
        >
        </FlatList>
    );

}

Posts.js:

 export default function FeedPosts(props) {
    return (
        <Container>
            <Header>
                <TouchableOpacity>
                    <FontAwesome5 name='bell' size={40} style={{ marginLeft: 10 }}></FontAwesome5>
                </TouchableOpacity>
                <TouchableOpacity>
                    <Ionicons name='add-circle' size={40} style={{ marginRight: 5 }}></Ionicons>
                </TouchableOpacity>
            </Header>
            <Body>
                <Time>15/12/2021 as 17:42pm</Time>
                <User>
                    <Icon source={require('../../assets/vibe.jpg')}></Icon>
                    <Description>{props.title}</Description>
                </User>

                <Content>
                    <PetPhoto source={props.postImg}></PetPhoto>
                </Content>

                <ContentDesc >
                    <PhotoDesc> {props.photoDesc}</PhotoDesc>
                </ContentDesc>

                <Bottom>
                    <Comment title="Comment" placeholder="Escrever Comentário"></Comment>
                </Bottom>
                <Buttons></Buttons>
            </Body>
        </Container>
    );
}

1 个答案:

答案 0 :(得分:0)

您的变量 Posts 包含一组 React 组件。相反,它应该包含您转换为组件的数据数组。

所以您的 Posts 应该看起来更像这样:

const Posts = [
 {title: "My title", photoDesc: "Desc"},
 {title: "My title2", photoDesc: "Desc2"},
 {title: "My title3", photoDesc: "Desc3"}
]

这是一个在上下文中如何工作的示例(直接来自 React Native 文档):

const DATA = [
  {
    id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
    title: 'First Item',
  },
  {
    id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
    title: 'Second Item',
  },
  {
    id: '58694a0f-3da1-471f-bd96-145571e29d72',
    title: 'Third Item',
  },
];

const Item = ({ title }) => (
  <View style={styles.item}>
    <Text style={styles.title}>{title}</Text>
  </View>
);

const App = () => {
  const renderItem = ({ item }) => (
    <Item title={item.title} />
  );

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={DATA}
        renderItem={renderItem}
        keyExtractor={item => item.id}
      />
    </SafeAreaView>
  );
}

(https://reactnative.dev/docs/flatlist)

您可以在上面的示例中看到 DATA 是一个对象数组,它通过函数 renderItem 转换为组件。与您的用例非常相似。