javascript - 如何在 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')
}
});
有什么解决办法吗?
解决方案
快速解决方案:
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 并用您选择的值覆盖
推荐阅读
- user-interface - Unity3D:如何检测按钮何时被按住和释放
- html - 溢出:隐藏和省略号在要隐藏的文本之前不与背景图像一起使用
- java - 如何修复我的代码,以便它可以找到我设置的密码标准
- angular - 如何以这样一种方式向用户授予对云 Firestore 的访问权限,使他们间接成为我的应用程序的一部分但未在我的 Firebase 控制台中注册?
- c# - 将 SQL Server 与 MySQL 一起使用时出现“不支持选项”错误
- clang - AOSP 构建系统如何生成 .rsp 文件以及如何获取它们?
- javascript - 如果用户未登录,则在登录表单中重定向用户
- mysql - How to find if a customer was contacted thrice over a period of two days?
- apache-flink - Flink - 如何实现自定义会话窗口,在特定事件上创建窗口并在一段时间后触发?
- python-3.x - 如何修复由 n_jobs = -1 导致的虚拟环境和 Jupyter notebook 中的“PermissionError: [WinError 5] Access is denied”