无法在本机反应中使用 FlatLists renderItem 中的项目值
Unable to use the item value from FlatLists renderItem in react native
我对编码还很陌生,所以真的很难解决这个问题,但我确信这很简单。
使用时 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: undefined is not an object (evaluating '_global.default.products[item].title
<Text>{GLOBAL.products[**{**item**}**].title}</Text>
不起作用。还有 _renderItem = ( **{**item**}** ) => {
.
<Text>{GLOBAL.products[9].title}</Text>
工作正常。也试过GLOBAL.products[parseInt(item)].title
很明显您不知道 JavaScript Object 和 child 调用。当你调用 child 但它的 parent 不存在时,你肯定也会在 React Native 的 Text
组件中遇到错误,你应该至少传递一个空字符串。
你应该开发 children 的链式呼叫防御性。为此,我建议您阅读有关 optional chaining and add it to your project by using 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 >
);
我更喜欢第二个。这种防御性编程可防止您的应用程序崩溃。
我对编码还很陌生,所以真的很难解决这个问题,但我确信这很简单。
使用时 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: undefined is not an object (evaluating '_global.default.products[item].title
<Text>{GLOBAL.products[**{**item**}**].title}</Text>
不起作用。还有 _renderItem = ( **{**item**}** ) => {
.
<Text>{GLOBAL.products[9].title}</Text>
工作正常。也试过GLOBAL.products[parseInt(item)].title
很明显您不知道 JavaScript Object 和 child 调用。当你调用 child 但它的 parent 不存在时,你肯定也会在 React Native 的 Text
组件中遇到错误,你应该至少传递一个空字符串。
你应该开发 children 的链式呼叫防御性。为此,我建议您阅读有关 optional chaining and add it to your project by using 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 >
);
我更喜欢第二个。这种防御性编程可防止您的应用程序崩溃。