[英]How do I dispatch an action to the correct key of a nested object in store.state in vuex?
[英]VUEX, what to do when $store.state is null
當用戶未登錄我的網站時, user
狀態設置為null
。 但是,這會在我查看this.$store.user
某些頁面上引發很多問題
例如,如果我要進行一個簡單的檢查,例如
if (this.$store.getters.userInfo.likedProjects.includes(title)) {this.hasLiked = true}
並且用戶未登錄(因此,默認情況下將用戶狀態設置為 null)我收到此錯誤;
_this.$store.getters.userInfo is null
我應該如何正確處理此類問題,以免我的控制台充斥着打字稿錯誤?
我最初的想法是首先檢查if user.loggedIn == true
並將所有內容都包含在其中,但這似乎非常混亂,只是為了避免一些錯誤......
if(this.$store.getters.userInfo){
if (this.$store.getters.userInfo.likedProjects.includes(title)) {this.hasLiked = true}
}
使用可選鏈,它在 TypeScript 3.7+ 中可用:
if (this.$store.getters.userInfo?.likedProjects.includes(title)) {
this.hasLiked = true;
}
如果userInfo
為 null 或 undefined,則整個語句this.$store.getters.userInfo?.likedProjects.includes(title)
將返回undefined
而不是拋出錯誤。
如果likedProjects
也可能為空或未定義,那么您也需要在該屬性上使用可選鏈,即:
if (this.$store.getters.userInfo?.likedProjects?.includes(title)) {
this.hasLiked = true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.