【问题标题】:React native, How to not call a value from an API if it is null?反应原生,如果它为空,如何不从 API 调用值?
【发布时间】:2020-11-22 18:07:07
【问题描述】:

在我的这个API 我想从推荐的配置中获取值,但有些值为空,所以我的应用程序给了我一个错误:null is not an object

这是我的代码:

let page1 = this.state.dataSource1.map((val, key) => {
    // if (val.platforms[0].requirements_en.minimum != null) {

    // }
    return (
        {val.platforms[0].requirements_en.recommended ==! null ?
            <Text style={styles.name}>minimal configuration : {val.platforms[0].requirements_en.recommended}</Text>
            :
            <Text>Nothing</Text>
        }
    )
})

我想说的是,如果值不为空,请将数据发送给我,否则为简单的文本,但它不起作用...

【问题讨论】:

  • 你的意思是!==
  • 它也不起作用。

标签: react-native api mobile null fetch


【解决方案1】:

您的代码中存在一些问题。

首先,您要返回一个对象,但您没有指定键。
因此,您要么需要添加一个,要么更可能这是一个错误,您需要删除 return 中的花括号。

其次,你有一个拼写错误 ==! 而不是 !==

第三,关于您的问题,您需要检查 API 返回的每个元素是否与可选链接运算符一起存在,如下所示:val?.platforms[0]?.requirements_en?.recommended
为了进一步扩展这一点,如果?. 之前的部分是nullundefined,则可选链接运算符将返回undefined
在您的情况下,有时 requirements_en 为空,因此您收到错误消息。

let page1 = this.state.dataSource1.map((val, key) => {
  return val?.platforms[0]?.requirements_en?.recommended ? (
    <Text key={key}>
      minimal configuration: {val.platforms[0].requirements_en.recommended}
    </Text>
  ) : (
    <Text>Nothing</Text>
  )
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多