簡體   English   中英

typeError: undefined 不是一個對象(評估“item.phoneNumbers[0]”)

[英]typeError: undefined is not an object (evaluating 'item.phoneNumbers[0]')

我想使用 expo-contacts 在我的應用程序中呈現我的聯系人列表,列表顯示大約 2 秒,然后我得到 typeError: undefined is not an object(評估“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>
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM