我试图从从API接收的数据创建一个SectionList。对于我想要显示的成分,这个API具有以下结构:
const ingredients = {
malt: [
{
name: 'Maris Otter Extra Pale',
amount: {
value: 3.3,
unit: 'kilograms',
},
},
{
name: 'Caramalt',
amount: {
value: 0.2,
unit: 'kilograms',
},
},
{
name: 'Munich',
amount: {
value: 0.4,
unit: 'kilograms',
},
},
],
hops: [
{
name: 'Fuggles',
amount: {
value: 25,
unit: 'grams',
},
add: 'start',
attribute: 'bitter',
},
{
name: 'First Gold',
amount: {
value: 25,
unit: 'grams',
},
add: 'start',
attribute: 'bitter',
},
{
name: 'Fuggles',
amount: {
value: 37.5,
unit: 'grams',
},
add: 'middle',
attribute: 'flavour',
},
{
name: 'First Gold',
amount: {
value: 37.5,
unit: 'grams',
},
add: 'middle',
attribute: 'flavour',
},
{
name: 'Cascade',
amount: {
value: 37.5,
unit: 'grams',
},
add: 'end',
attribute: 'flavour',
},
],
yeast: 'Wyeast 1056 - American Ale™',
};
使用SectionList(以麦芽和啤酒花作为节头)得到的期望结果如下:
结果的可视化示例
我已经尝试过使用Object.values()这样的函数,但根本没有结果。代码如下所示,从前一个视图接收啤酒(带有啤酒列表):
const Detail = ({ route }) => {
const beer = route.params.beer;
const ingredientsFormatted = Object.values(beer.ingredients);
return(
<SectionList
sections={ingredientsFormatted}
renderItem={({ item }) => {
<Text>{item.name}</Text>; //Here there has to be the name of the different ingredients
}}
renderSectionHeader={({ section }) => <Text>{section}</Text>} //Here there has to be malt, hops or yeast
keyExtractor={(item) => item.name}
></SectionList>
)}
你的ingredients
数据有两个问题。
yeast
的值格式与其他的不一样。- 你插入到SectionList中的数据不是React-Native官方文档推荐的格式。
要解决这个问题,您可以修改API返回/映射从服务器检索到的数据。
const Detail = ({ route }) => {
const beer = route.params.beer;
let sectionListTemplate = [];
for (let [key, value] of Object.entries(beer.ingredients)) {
//console.log(`${key}: ${JSON.stringify(value)}`);
if(!Array.isArray(value)){
//Handle case for 'yeast' which its data is not an array
sectionListTemplate.push({
title: key,
data: [{
name: value
}]
})
}
else{
//Map value for general cases
sectionListTemplate.push({
title: key,
data: value
})
}
}
return(
<SectionList
sections={sectionListTemplate}
renderSectionHeader={({ section }) => {
return(
//Here there has to be malt, hops or yeast
<Text style={{fontWeight: 'bold'}}>
{section.title}
</Text>
)
}}
renderItem={({ item }) => {
return(
//Here there has to be the name of the different ingredients
<Text>
{item.name}
</Text>
)
}}
keyExtractor={(item) => item.name}
>
</SectionList>
)
)}