在 React Native 中使用 Flatlists renderItem,如果我使用 Item 的值作为数组的索引,它是未定义的
with Flatlists renderItem in react native, if I use the value of Item as an index of an array, it is undefined
当访问传递给 _renderItem
的 item
时,我可以像这样使用值 <Text>{item.item}</Text>
并打印 1、2,但不能将其用作数组的索引像这样 <Text>{get(GLOBAL, ['products', 'item.item', 'title'], '')}</Text>
其中 returns 是一个空字符串。
import get from 'lodash.get';
~~~
_renderItem = (item) => {
return (
<View style={{ flex: 1 }}>
<Text>{item.item}</Text>
<Text>{get(GLOBAL, ['products', 'item.item', 'title'], '')}</Text>
</View >
)
};
render() {
return (
<View style={styles.list}>
<FlatList
data={[1,2]}
renderItem={this._renderItem} />
</View>
)
}
<Text>{get(GLOBAL, ['products', 'item.item', 'title'], '')}</Text>
这输出 ''
但 <Text>{get(GLOBAL, ['products', '1', 'title'], '')}</Text>
按预期输出。
为什么这些响应不同,我如何使用传入 item
到 _renderItem
的值作为数组的索引?
原因是传递给 FlatList 的数据对应于我要从中获取某些信息的产品的索引。
感谢任何帮助!
不要忘记是:_renderItem = ({item})
不是_renderItem = (item)
您想使用项目值而不是对象和 属性,您要传递一个字符串作为参数来连接 lodash.get
对象。尝试这样做:
_renderItem = (item) => {
return (
<View style={{ flex: 1 }}>
<Text>{item.item}</Text>
<Text>{get(GLOBAL, ['products', item.item, 'title'], '')}</Text>
</View >
)
};
当项目是 1
而不是您现在拥有的 GLOBAL['products']['item.item']['title']
时,实际上会得到 GLOBAL['products'][1]['title']
。
当访问传递给 _renderItem
的 item
时,我可以像这样使用值 <Text>{item.item}</Text>
并打印 1、2,但不能将其用作数组的索引像这样 <Text>{get(GLOBAL, ['products', 'item.item', 'title'], '')}</Text>
其中 returns 是一个空字符串。
import get from 'lodash.get';
~~~
_renderItem = (item) => {
return (
<View style={{ flex: 1 }}>
<Text>{item.item}</Text>
<Text>{get(GLOBAL, ['products', 'item.item', 'title'], '')}</Text>
</View >
)
};
render() {
return (
<View style={styles.list}>
<FlatList
data={[1,2]}
renderItem={this._renderItem} />
</View>
)
}
<Text>{get(GLOBAL, ['products', 'item.item', 'title'], '')}</Text>
这输出 ''
但 <Text>{get(GLOBAL, ['products', '1', 'title'], '')}</Text>
按预期输出。
为什么这些响应不同,我如何使用传入 item
到 _renderItem
的值作为数组的索引?
原因是传递给 FlatList 的数据对应于我要从中获取某些信息的产品的索引。
感谢任何帮助!
不要忘记是:_renderItem = ({item})
不是_renderItem = (item)
您想使用项目值而不是对象和 属性,您要传递一个字符串作为参数来连接 lodash.get
对象。尝试这样做:
_renderItem = (item) => {
return (
<View style={{ flex: 1 }}>
<Text>{item.item}</Text>
<Text>{get(GLOBAL, ['products', item.item, 'title'], '')}</Text>
</View >
)
};
当项目是 1
而不是您现在拥有的 GLOBAL['products']['item.item']['title']
时,实际上会得到 GLOBAL['products'][1]['title']
。