[英]JSON Object Property not returnable - “Cannot Read Property of Undefined”
好的,所以我在 React 中構建了一個自定義 API。 當我撥打電話時,我將返回 JSON 數據並使用 JSON.Stringify 將其存儲到本地存儲中:
localStorage.setItem('user', JSON.stringify(response.data))
稍后,我將這個項目調用到主頁上,以便在用戶使用以下方式登錄后返回一些數據:
var user = JSON.parse([localStorage.getItem('user')])
這將返回 object:
{
"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}
實際上會返回 object,但顯然不能將其打印到字符串中。 返回{user.LoginInfo["ConstituentId"]}
會導致錯誤:
Uncaught TypeError: Cannot read property 'ConstituentId' of undefined
所以,是的,我很難過,我不知道我是如何錯誤地返回這個的。 任何幫助表示贊賞。
使用擴展運算符來獲得你想要的東西怎么樣?
const user = JSON.parse(localStorage.getItem('user'))
const { ConstituentId, UserId } = user.LoginInfo
console.log(ConstituentId) // 190554
這段代碼對我有用:
localStorage.setItem("user", JSON.stringify({
"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
}));
const user = JSON.parse(localStorage.getItem("user"));
console.log(user.LoginInfo.OriginalConstituentId);
好的,所以我返回這些值的方式似乎是一個“問題”,因為 React 處理它的 Render 事件的方式。 當我在componentDidMount()
事件中提取數據時,Render 事件仍然會在此之前觸發。
componentDidMount() {
this.setState({
user: JSON.parse([localStorage.getItem('user')]),
users: { loading: true }
});
}
所以在渲染事件中:
render() {
const { user, users, loading } = this.state;
var { ConstituentId, UserId } = user.LoginInfo
return (
<div className="col-md-6 col-md-offset-3">
<h1>Hi!</h1>
<p>{UserId}</p>
<p>You're logged in with React & Basic HTTP Authentication!!</p>
<h3>Users from secure api end point:</h3>
<p>
<Link to="/login">Logout</Link>
</p>
</div>
);
}
它觸發兩次,一次在state.user
之前由componentDidMount()
設置,然后再次觸發。 因此,由於第一次觸發 Render,我的代碼出錯了,沒有設置任何內容,因此出現了undefined
的消息。 我想出了如何通過檢查登錄信息 object 返回為typeof object
來繞過這個問題。 這是在我的渲染事件中:
var result = (typeof user.loginInfo === 'object');
if (result && loading) {
console.log(result)
console.log(user.LoginInfo.ConstituentId)
var { ConstituentId, UserId } = user.LoginInfo
}
但這不是很優雅。 因此,最終我通過創建一個名為“加載”的 state 道具重新編寫了我在componentDidMount()
中處理卸載信息的方式:
this.state = {
loading: true,
user: {}
};
在componentDidMount()
我這樣做:
this.setState({
user: JSON.parse(localStorage.getItem('user')),
loading: false
});
在render()
中:
const { loading, user } = this.state;
if (!loading) {
var { ConstituentId, UserId } = user.LoginInfo
}
console.log(ConstituentId)
效果很好!
基本上,我只是在等待componentDidMount()
使用loading
state 通過在 function 中將其設置為false
來觸發。 然后我們知道它已經加載並且可以成功渲染數據了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.