繁体   English   中英

React.js 处理 json 中的缺失数据(TypeError: Cannot read property 'prefix' of null)

[英]React.js deal with missing data in json (TypeError: Cannot read property 'prefix' of null)

我读了 API 但 json 结果并不总是“完整的”。 在第 2 行中缺少年龄。

 {
     ["name": "Max", "age":15, "country": 1],
     ["name": "Muster", "country": 56],
     ["name": "Test", "age": 5, "country": 5]
 }

当我尝试通过数组执行 map 时,我得到“TypeError:无法读取 null 的属性‘年龄’)

{items.map((res, index) => (
    <p>
        {res.name}
        {res.age}
        {res.country}
     </p>
))}

处理 JSON 响应中缺失数据的最佳方法是什么?

下面的数据结构看起来很奇怪:

{
     ["name": "Max", "age":15, "country": 1],
     ["name": "Muster", "country": 56],
     ["name": "Test", "age": 5, "country": 5]
}

但是,您可以为此使用safe operator

 {res?.age ?? ''} // empty string will be returned in case res == null or undefined

工作演示

编辑 so-react-safe-operator

您可以检查属性是否存在:{res.age? res.age: ''}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM