【问题标题】:React Native hooks with null GraphQL Data使用 null GraphQL 数据反应原生钩子
【发布时间】:2020-09-07 11:54:49
【问题描述】:

我正在使用 react native hooks 将数据从我的主屏幕传递到辅助屏幕,但是我返回的一些数据将为空。

const { profileData } = navigation.state.params;

这会导致如下错误: “未捕获的 TypeError:无法读取 null 的属性‘阶段’”

这来自我的辅助屏幕上的这个 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)
        }
    })

我怎样才能让它不关心某些用户的阶段字段为空?

【问题讨论】:

    标签: react-native graphql react-hooks


    【解决方案1】:

    “Cannot read property 'stage' of null”实际上是在告诉你levelRequestnull。这当然意味着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 中以更多的专业知识和细节进行了讨论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-08
      • 2023-03-14
      • 1970-01-01
      • 2021-09-05
      • 1970-01-01
      • 2020-08-09
      • 2021-06-29
      • 1970-01-01
      相关资源
      最近更新 更多