我正在使用react native钩子将数据从主屏幕传递到辅助屏幕,但是我返回的某些数据将为空。
const { profileData } = navigation.state.params;
这会导致如下错误:“未捕获的TypeError:无法读取null的属性'stage'”
哪个来自此useEffect在我的辅助屏幕上:
useEffect(() => {
if(profileData.item.levelrequest.stage == "Submitted") {
setlrequest05(true)
} else if(profileData.item.levelrequest.stage == "") {
setlrequest05(false)
} else if(profileData.item.levelrequest.stage == "Approved") {
setlrequest05(false)
}
})
我如何让它不在乎某些用户的stage字段为空?
“无法读取null的属性'stage'实际上是告诉您levelRequest
为null
。这当然可以意味着stage
的任何一个父母都是null
...并且JS中没有任何魔术方法可以绕过实际检查对象的每个级别以确保它存在。
您可以通过使那些字段为必填字段来加强服务器上的架构,但是处理此问题的最直接方法是在函数的开头编写一个“后卫”条件,例如:
useEffect(() => {
if (!profileData ||
!profileData.item ||
!profileData.item.levelRequest ||
!profileData.item.levelRequest.stage) {
// do something to handle null data...probably `return` so the other
// conditional of the hook isn't fired
}
...rest of your function here...
})
这是一个粗略的示例,但它表达了这个想法。在this thread中将更详细地讨论这种情况。