首页 > 解决方案 > React Native 联系人:null 不是对象

问题描述

我正在开发一个 React Native 应用程序,我需要将一个新联系人保存到手机中。通过研究,我发现有 3 个库实现了该功能:expo-contacts、react-native-contacts 和 react-native-unified-contacts。在每一个中,我都遵循了安装说明,但在每一个中,我一直遇到相同的错误:

Possible Unhandled Promise Rejection (id: 0):
TypeError: null is not an object (evaluating '_reactNativeUnifiedContacts.default.getContacts')
http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:150346:52
tryCallOne@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:27023:16
http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:27124:27
_callTimer@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:30578:17
_callImmediatesPass@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:30614:19
callImmediates@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:30833:33
callImmediates@[native code]
__callImmediates@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2625:35
http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2402:34
__guard@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2608:15
flushedQueue@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2401:21
flushedQueue@[native code]
invokeCallbackAndReturnFlushedQueue@[native code]

这个确切的错误来自 react-native-unified-contacts,但它们都抛出“null is not an object”错误。首先,我虽然可能是链接问题,但由于我有 React Native 0.61 版本,链接是自动完成的。所以,我一直有这个错误,我无法添加任何联系人。

标签: androidreact-nativecontacts

解决方案


尝试在 .then() 之后添加一个 catch 块,它解决了我的问题。

PermissionsAndroid.request(
            PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
            {
              'title': 'Contacts',
              'message': 'This app would like to view your contacts.'
            }
          ).then(() => {
            con.getAll((err, contacts) => {
              if (err === 'denied'){
                // error
              } else {
                // contacts returned in Array
                console.log(contacts);
              }
            })
          })
          .catch((err)=> {
              console.log(err);
          })

推荐阅读