FlatList 呈现空孩子
FlatList rendering empty childs
我似乎无法在 FlatList 中渲染子项。
所以,我正在创建一个集换式卡片组构建应用程序。作为数据库,我使用的 json 文件包含大约 1300 张卡片 objects.
卡片屏幕:
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 object 的所有 ID 并创建了一个简单的数组 (state.cards)。通常我会使用 Card 组件来渲染它,但列表似乎是空的,所以我想,作为测试,渲染 id 本身。
我清楚地看到 1000 多条文本 "id=" 正在呈现,不幸的是没有 id 值。
不确定我做错了什么。
您传递给 renderItem
的函数接收包装在对象中的数据条目作为参数:
{
item: {... your object ...}
}
所以要获得它,您可以执行以下操作:
renderItem={({item}) => <Text>id={cards[item.id]}</Text>}
renderItem
还在该对象中发送了更多内容。看看here.
我似乎无法在 FlatList 中渲染子项。
所以,我正在创建一个集换式卡片组构建应用程序。作为数据库,我使用的 json 文件包含大约 1300 张卡片 objects.
卡片屏幕:
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 object 的所有 ID 并创建了一个简单的数组 (state.cards)。通常我会使用 Card 组件来渲染它,但列表似乎是空的,所以我想,作为测试,渲染 id 本身。
我清楚地看到 1000 多条文本 "id=" 正在呈现,不幸的是没有 id 值。
不确定我做错了什么。
您传递给 renderItem
的函数接收包装在对象中的数据条目作为参数:
{
item: {... your object ...}
}
所以要获得它,您可以执行以下操作:
renderItem={({item}) => <Text>id={cards[item.id]}</Text>}
renderItem
还在该对象中发送了更多内容。看看here.