React Native:FlatList 索引表示未定义

React Native: FlatList index says is undefined

我正在尝试在 React Native 中检索 FlatList 上被单击元素的索引。 正如文档所说,我将索引传递给 renderItem 道具。我的代码如下:

/**
 * Goes to the show view of a container
 * @param {*} index 
 */
showContainer = (index) => {
    console.log(index); 
}

render() {
    return (
        <DefaultScrollView style={styles.container}>
            <FlatList
                data={this.props.containers}
                renderItem={(data, index) => (
                    <ListItem
                        containerStyle={{borderBottomWidth: 1, borderBottomColor: "#000"}}
                        key={data.item.id}
                        leftAvatar={Image}
                        onPress={() => {this.showContainer(index)}}
                        rightIcon={{ name: "ios-eye", type: "ionicon" }}
                        subtitle={
                            `${data.item.dummy === true? 'Por favor configura tu dispositivo' : 'Contenido actual: '}`
                        }
                        subtitleStyle={(data.item.dummy == true)? [styles.configurationText, styles.subtitule] : styles.subtitule}
                        title={data.item.name}
                        titleStyle={styles.title}
                    />
                )}/>
        </DefaultScrollView>
    );
}

唯一可行的方法是我传递一个数字作为索引,例如: renderItem={(data, index = 0),但我怎样才能传递索引变量以始终拥有正确的索引?

提前致谢

只需将 data, index 换成 {} 并将每个 data 更改为 item,

  renderItem={({item, index}) => ( ....
              ....
              key={item.item.id} // like this every where

代码中的问题是:

您的代码:

   renderItem={(data, index) => ( 

正确一个:

 renderItem={({ item, index }) => (

您可以更新您的 renderItem,它将解决您的问题。:

renderItem={({ item, index }) => (
           <ListItem
                        containerStyle={{borderBottomWidth: 1, borderBottomColor: "#000"}}
                        key={data.item.id}
                        leftAvatar={Image}
                        onPress={() => {this.showContainer(index)}}
                        rightIcon={{ name: "ios-eye", type: "ionicon" }}
                        subtitle={
                            `${data.item.dummy === true? 'Por favor configura tu dispositivo' : 'Contenido actual: '}`
                        }
                        subtitleStyle={(data.item.dummy == true)? [styles.configurationText, styles.subtitule] : styles.subtitule}
                        title={data.item.name}
                        titleStyle={styles.title}
                    />
        )}

您需要解构您的数据,然后再将其传递给renderItem

所以改变:

 renderItem={(data, index) => ( ...

收件人:

 renderItem={({item, index}) => (...

然后您可以使用 item.id 访问您的数据。

简化的工作演示:

https://snack.expo.io/B1AONkehN