【问题标题】:React-Native, error dissapears after I reload the app, but then appears againReact-Native,重新加载应用程序后错误消失,但又出现
【发布时间】:2020-05-23 19:18:58
【问题描述】:

最近我遇到了两个非常奇怪的问题。当我尝试从 cloud-firestore 加载查询时

<Text style={styles.bold}>{user.followers.includes(this.props.user.uid) ? 'UnFollow User' : 'Follow User'}</Text>

我得到错误: TypeError: undefined is not an object (evalating 'user.followers.indexOf')。 但是,当我删除这一行,然后保存文档,然后立即再次添加 same 行并保存时,代码可以正常工作,直到我再次关闭我的应用程序,错误再次出现。

此外,我再次遇到了由平面列表中的一行引起的相同错误

data={this.props.messages.filter(message => message.members.indexOf(params) >= 0 && message.members.indexOf(this.props.user.uid) >= 0)} 

当我删除 .filer(..) 部分时,错误消失了 但是,与第一种情况类似,在我再次添加该行并保存后它不会出现。 错误:TypeError: undefined is not an object (near'...this.props.messages.filter...')

我认为该错误可能与从 firebase 加载数据有关。提前致谢。

【问题讨论】:

    标签: javascript firebase react-native filter google-cloud-firestore


    【解决方案1】:

    可能的原因是对象未定义。

    您对关注者的第一个场景: 如果 user.followers 未定义,并且当您访问未定义的包含方法时,将导致错误。加载关注者数组后,您的应用程序将正常工作。 您可以简单地添加一个如下所示的检查,该检查将在加载属性之前显示关注用户,或者您可以在加载所有内容后简单地呈现内容。

    <Text style={styles.bold}>{user?.followers?.includes(this.props.user.uid) ? 'UnFollow User' : 'Follow User'}</Text>
    

    this.props.messages 的情况也是如此,只要未定义此 prop,您可以在过滤之前检查消息是否具有值,并设置数据的值,以确保您不会遇到运行时错误。

    你可以像下面这样更新第二部分

    data={this.props.messages && this.props.messages.filter(message => message.members.indexOf(params) >= 0 && message.members.indexOf(this.props.user.uid) >= 0)}
    

    【讨论】:

    • 谢谢,这对我有用!我应该如何在第二个例子中实现它?我试过data={this.props?.messages?.filter(message =&gt; message.members.indexOf(params) &gt;= 0 &amp;&amp; message.members.indexOf(this.props.user.uid) &gt;= 0)} 但我得到错误这不是一个函数'..._this$props$messages.filter
    • 不幸的是,我仍然在第二个中遇到错误:udnefined is not a function (near 'this.props.messages,filer...)
    • 能否请您向我解释一下第二部分的工作原理?我真的不明白发生了什么
    • 消息是一个数组吗?如果不是,您应该使用 Array.isArray(this.props.messages) 作为第一个条件
    • 为第二部分添加了一些描述:)
    猜你喜欢
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    相关资源
    最近更新 更多