【发布时间】:2020-08-06 00:44:34
【问题描述】:
好的,所以我在 React 中构建了一个自定义 API。当我拨打电话时,我会取回 JSON 数据并使用 JSON.Stringify 将其存储到本地存储中:
localStorage.setItem('user', JSON.stringify(response.data))
稍后,我将这个项目调用到主页上,以便在用户使用以下方式登录后返回一些数据:
var user = JSON.parse([localStorage.getItem('user')])
这会返回对象:
{
"OrderId":0,
"IsLoggedIn":true,
"ModeOfSaleId":64,
"OriginalModeOfSaleId":64,
"SourceId":8580,
"LoginInfo":{"ConstituentId":190554,"OriginalConstituentId":190554,"UserId":"test@email.org","Status":"P","FailedAttempts":0,"LockedDate":null,"ElectronicAddress":"test@email.org"},
"CartInfo":{"PerformanceCount":0,"PackageCount":0,"ContributionCount":0,"MembershipCount":0,"UserDefinedFeeCount":0,"GiftCertificateCount":0,"PaymentCount":0,"FirstSeatAddedDateTime":null},
"BusinessFacing":false,
"IsGuest":false,
"CheckoutStatus":{"Status":"No Checkout","Date":null},
"HasLockedSeats":false,
"SeatsExpired":false
}
问题:
未嵌套的属性正常返回{user.OrderId} 或{user.ModeOfSaleId} 但是,尝试返回嵌套值如{user.LoginInfo.ConstituentID} 会导致错误:
Uncaught TypeError: Cannot read property 'ConstituentId' of undefined
返回{user.LoginInfo} 实际上会返回一个对象,但显然不能将其打印到字符串中。返回{user.LoginInfo["ConstituentId"]} 会导致错误:
Uncaught TypeError: Cannot read property 'ConstituentId' of undefined
所以是的,我很难过,我不知道我是如何错误地返回这个的。任何帮助表示赞赏。
【问题讨论】:
标签: javascript json reactjs api parsing