首页 > 解决方案 > 如何在 JSON api 中显示空值代替未定义的值?

问题描述

在weather api中,有些值为null,在主页上显示为未定义(见底部的图像),占用最大空间。如何将这些空值替换为空值,即“”或“NA”?

下面是代码

fetch(`${IP_LOCATION}&lat=${lat}&long=${lon}`)
  .then(res => res.json()).then(responseJson => {
    try {
      this.setState({
        sunrise: responseJson.sunrise,
        sunset: responseJson.sunset,
        // Here I get undefined
        moonrise: responseJson.moonrise,
        moonset: responseJson.moonset,
      })

    } catch {
      toast.error('No Data Received')
    }

  });

在此处输入图像描述

有什么解决办法吗?

标签: javascript

解决方案


快速解决方案:

try {
      this.setState({
        sunrise: responseJson.sunrise,
        sunset: responseJson.sunset,

        // replace with this line 
        moonrise: responseJson.moonrise ? responseJson.moonrise : " ",

        moonset: responseJson.moonset,
      })

    } catch {
      toast.error('No Data Received')
    }

(编辑)使用三元运算符,您可以检查 null 或 undefined 并用您选择的值覆盖


推荐阅读