【发布时间】:2019-06-01 18:21:24
【问题描述】:
下面的代码显示了 2 个应该将组件渲染到屏幕的函数。当我通过数组进行映射时,组件会呈现。问题是当我尝试通过数组中的对象内的数组进行映射时,组件不会呈现。
假设我们有这个数据集:
const categories = [
{
title: "Burgers",
items: [
{
item_number: 0,
name: "Cheese Burgers"
},
{
item_number: 1,
name: "Double Cheese Burgers"
},
{
item_number: 2,
name: "Triple Cheese Burgers"
}
]
}
];
然后我们就有了这个渲染函数:
render() {
const { backgroundImage, menuIndex } = this.props.screenProps;
return (
<View>
{/*THIS DOES RENDER*/}
{categories ? (
categories.map((category, i) => (
<Card key={i} image={backgroundImage}>
<Text style={{ marginBottom: 10 }}>{category.title}</Text>
</Card>
))
) : (
<ActivityIndicator style={styles.center_screen} />
)}
{/*THIS DOES NOT RENDER*/}
{categories ? (
categories[menuIndex].items.map((item, i) => {
<View key={i}>
{console.warn(item.name)}
<Text>{item.name}</Text>
</View>;
})
) : (
<ActivityIndicator style={styles.center_screen} />
)}
</View>
);
}
}
变量“类别”是从 API 调用的,当它在路由中时,活动指示器会显示。当它不为空时,我可以映射数组并显示每个对象的文本。但是,当我尝试通过数组对象内的数组进行映射时,我无法将文本呈现到屏幕上。当我将警告记录到屏幕上时,我可以看到“item.name”,但在文本组件中看不到。
这是如何以及为什么会发生的?
【问题讨论】:
-
你检查过 categories[menuIndex] 是否返回一个对象吗?
-
是的,我可以在 YellowBox 组件中看到它,但在 Text 组件中看不到。
-
您是否尝试删除黄色框?只是一种预感。可能已停止渲染。
-
当你有一个箭头函数并开始一个块
{}语句,没有隐式返回,它需要一个显式的return语句,你可以,替换括号中的花括号使隐式返回起作用,或显式使用return语句... -
非常好!我现在刚换了。
标签: javascript arrays reactjs react-native ecmascript-6