gpt4 book ai didi

javascript - 类型错误 : undefined is not an object (evaluating 'item.phoneNumbers[0]' )

转载 作者:行者123 更新时间:2023-11-30 19:21:48 25 4
gpt4 key购买 nike

我想在我的应用程序中使用 expo-contacts 呈现我的联系人列表,列表显示大约 2 秒,然后我得到类型错误:未定义不是对象(评估“item.phoneNumbers [0]”)。我已经检查了文档以查看我是否犯了任何错误,但我找不到任何错误。有没有人能解决这个问题

下面是我的代码

联系人列表.js

import React, { Component } from "react";
import {
View,
Text,
Platform,
StatusBar,
FlatList,
StyleSheet,
ActivityIndicator
} from "react-native";
import * as Contacts from "expo-contacts";
import * as Permissions from "expo-permissions";

class ContactList extends Component {
static navigationOptions = {
header: null
};

constructor(props) {
super(props);
this.state = {
isLoading: false,
contacts: []
};
}

async componentDidMount() {
this.setState({
isLoading: true
});

this.loadContacts();
}

loadContacts = async () => {
const permissions = await Permissions.askAsync(Permissions.CONTACTS);

if (permissions.status !== "granted") {
return;
}

const { data } = await Contacts.getContactsAsync({
fields: [Contacts.Fields.PhoneNumbers, Contacts.Fields.Emails]
});

this.setState({
contacts: data,
isLoading: false
});
};

handleBack() {
this.props.navigation.goBack();
}

renderItem = ({ item }) => (
<View style={{ minHeight: 70, padding: 5 }}>
<Text>
{item.firstName}
{item.lastName}
</Text>
<Text>{item.phoneNumbers[0].digits}</Text>
</View>
);

render() {
const { isLoading, contacts } = this.state;
let emptyContact = null;

emptyContact = (
<View style={styles.emptyContactStyle}>
<Text style={{ color: "red" }}>No Contacts Found</Text>
</View>
);

return (
<SafeAreaView style={styles.contentWrapper}>
<View style={styles.contentWrapper}>
{isLoading ? (
<View style={styles.isLoadingStyle}>
<ActivityIndicator size="large" color="#2484E8" />
</View>
) : null}
<FlatList
data={contacts}
renderItem={this.renderItem}
keyExtractor={(item, index) => index.toString()}
ListEmptyComponent={emptyContact}
/>
</View>
</SafeAreaView>
);
}
}

最佳答案

这是一个新的答案,因为以前的答案是题外话。出现此错误是因为显示的联系人没有 phoneNumber

您应该先检查电话号码是否存在,然后再显示它:

renderItem = ({ item }) => (
<View style={{ minHeight: 70, padding: 5 }}>
<Text>
{item.firstName}
{item.lastName}
</Text>
<Text>
{item.phoneNumbers && item.phoneNumbers[0] && item.phoneNumbers[0].digits}
</Text>
</View>
);

关于javascript - 类型错误 : undefined is not an object (evaluating 'item.phoneNumbers[0]' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57376168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com