FlatList呈现空孩子

时间:2018-11-24 09:23:51

标签: react-native react-native-flatlist

在FlatList中呈现子元素似乎有问题。

因此,我正在创建一个交易卡套构建应用程序。作为数据库,我正在使用带有1300个卡片对象的json文件。

CardScreen:

export default class CardsScreen extends React.Component {

constructor() {
    super();

    this.state = {
        cards: []
    }
}

componentDidMount() {
    this.setState({
        cards: cardsService.getCardsIds()
    });
}

render() {
    const {cards} = this.state;

    return (
        <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
            <View>
                <Text>Cards Screen</Text>
                <Text>Number of cards: {cards.length}</Text>
            </View>
            <View>
                <FlatList
                    data={cards}
                    renderItem={(id) => <Text>id={cards[id]}</Text>}
                    keyExtractor={(id) => 'card-${id}'}
                />
            </View>
        </View>
    );
}

}

在componentDidMount期间,我检索每个json对象的所有ID,并创建一个简单的数组(state.cards)。通常我会使用Card Component来渲染它,但是列表似乎是空的,因此我认为作为测试,可以渲染ID本身。

我很清楚地看到1000多个文本“ id =“,但是没有id值。

不知道我在做什么错了。

1 个答案:

答案 0 :(得分:2)

您传递给renderItem的函数将包装在对象中的数据条目作为参数接收:

{
  item: {... your object ...}
}

因此,您可以执行以下操作:

renderItem={({item}) => <Text>id={cards[item.id]}</Text>}

renderItem还在该对象中发送了更多内容。看看here

相关问题