我对编码非常陌生,因此确实为此感到吃力,但我敢肯定这很简单。
使用Flatlist
renderItem
item
_renderItem = ( item ) => {
return (<View style={{ flex: 1 }}>
<Text>{item}</Text>
<Text>{GLOBAL.products[item].title}</Text>
</View >)
};
render() {
return (
<View style={styles.list}>
<FlatList
data={[9,10]}
renderItem={ this._renderItem} />
</View>
)
}
<Text>{item}</Text>
工作正常,首先渲染9,然后渲染10。
但是<Text>{GLOBAL.products[item].title}</Text>
给我错误:
TypeError:TypeError:未定义不是一个对象(正在评估'_global.default.products [item] .title
<Text>{GLOBAL.products[**{**item**}**].title}</Text>
不起作用。还有_renderItem = ( **{**item**}** ) => {
。
<Text>{GLOBAL.products[9].title}</Text>
工作正常。也尝试过GLOBAL.products[parseInt(item)].title
答案 0 :(得分:0)
很明显,您不了解JavaScript对象和子调用。当您调用一个孩子但它的父母不存在时,您肯定在React Native的Text
组件中也出错,您应该至少传递一个空字符串。
您应该防御性地发展孩子们的连锁活动。为此,我向您提供有关optional chaining的信息,并使用this link将其添加到您的项目中。
安装后,您可以编写_renderItem
函数,如下所示:
_renderItem = item => (
<View style={{ flex: 1 }}>
<Text>{item}</Text>
<Text>{GLOBAL?.products[item]?.title || ''}</Text>
</View >
);
或者有一种更好的方法来使用lodash.get
,方法是将其与yarn add lodash.get
或npm install --save lodash.get
一起安装,然后像下面这样使用:
import get from 'lodash.get';
~~~
_renderItem = item => (
<View style={{ flex: 1 }}>
<Text>{item}</Text>
<Text>{get(GLOBAL, ['products', 'item', 'title'], '')}</Text>
</View >
);
我喜欢第二个。这种防御性的编程可以防止您的应用崩溃。