[英]Getting "TypeError: Cannot read properties of undefined" when trying to access properties of an object
[英]Getting undefined when trying to access properties in array object
我被困了两天试图访问数组对象的属性。 我可以在控制台中看到这些属性存在,但由于某种原因我无法访问它们。
当组件使用 React-Native 安装/useEffect 时,我正在加载用户联系人,然后我将它们传递给一个函数以过滤并仅返回电话号码。
这是加载联系人、setState 并进行异步后端调用的异步函数:
async function getAvailableContacts(contactArray) {
try {
const phoneNumbers = filterPhoneNumbers(contactArray);
const contactsWhoUseApp = await axios.post(
`${process.env.REACT_APP_backend_url}/available-contacts`,
{ phoneNumbers }
);
const newContacts = await getContacts(
contactArray,
contactsWhoUseApp.data
);
setRenderedContacts((prev) => newContacts);
} catch (error) {
console.log(error);
}
}
useEffect(() => {
(async () => {
const { status } = await Contacts.requestPermissionsAsync();
if (status === "granted") {
const { data } = await Contacts.getContactsAsync({
fields: [Contacts.Fields.PhoneNumbers],
});
if (data.length > 0) {
setContactArray((prev) => data);
getAvailableContacts(contactArray);
}
}
})();
}, []);
这是我将数组传递给的函数:
export function filterPhoneNumbers(contacts) {
let arrOfPhoneNumbers = [];
for (let i = 0; i < contacts.length; i++) {
console.log(contacts[i].phoneNumbers[0]);
}
return arrOfPhoneNumbers;
}
当我 console.log contacts[i]
这就是我所看到的:
Object {
"contactType": "person",
"firstName": "none",
"id": "123",
"imageAvailable": false,
"lastName": "none",
"lookupKey": "1234567",
"name": "none none",
"phoneNumbers": Array [
Object {
"id": "12",
"isPrimary": 1,
"label": "mobile",
"number": "+9999999999",
"type": "2",
},
Object {
"id": "12345",
"isPrimary": 0,
"label": "mobile",
"number": "+9999999999",
"type": "2",
},
],
}
但是在尝试访问 phoneNumbers 属性时出现此错误:
undefined is not an object (evaluating 'contacts[i].phoneNumbers[0]')
但是,当我 console.log 并从phoneNumbers[0]
中删除[0]
时,我可以看到 phoneNumbers 数组:
Array [
Object {
"id": "123",
"isPrimary": 1,
"label": "mobile",
"number": "+9999999999",
"type": "2",
},
Object {
"id": "1234",
"isPrimary": 0,
"label": "mobile",
"number": "+9999999999",
"type": "2",
},
]
任何人都遇到过类似的问题并且知道我做错了什么?
我看不出你的代码是如何抛出这个错误的,除非你把 undefined 放在你的联系人数组中的某个地方。
您实际上并没有将联系人传递给您的过滤器功能。
// Schedule a re-render where contactArray will become data
setContactArray((prev) => data);
// Send the OLD contactArray into getAvailableContacts
// since it hasn't been updated yet
getAvailableContacts(contactArray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.