axios 从React.js中的复杂JSON获取数据

qojgxg4l  于 2022-11-05  发布在  iOS
关注(0)|答案(1)|浏览(169)

我尝试使用www.example.com访问city属性postItem.address.city但它抛出了city未定义的错误

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },

上面是一个来自api的对象数组示例,下面是我尝试访问数据的方法:

{posts.map((postItem) => (
            <tr key={postItem.id}>
              <td>{postItem.id}</td>
              <td>{postItem.name}</td>
              <td>{postItem.username}</td>
              <td>{postItem.address.city}</td>
              <td>{postItem.email}</td>
              <td>

除city属性外,其他属性都运行良好
以下是错误:

Posts.js:43 

       Uncaught TypeError: Cannot read properties of undefined (reading 'city')
    at Posts.js:43:1
    at Array.map (<anonymous>)
    at Posts (Posts.js:37:1)
    at renderWithHooks (react-dom.development.js:14803:1)
    at updateFunctionComponent (react-dom.development.js:17034:1)
    at beginWork (react-dom.development.js:18610:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237:1)
    at invokeGuardedCallback (react-dom.development.js:292:1)
    at beginWork$1 (react-dom.development.js:23203:1)
bybem2ql

bybem2ql1#

问题似乎是您的传入地址中没有城市。处理此问题的现代方法是使用optional chaining。而不是以下代码:

<td>{postItem.address.city}</td>

你可以试试这个:

<td>{postItem.address?.city}</td>

但是,这会给您留下一条undefined消息,这并不好,因此您可以这样做:

<td>{postItem.address?.city || 'Unknown City'}</td>

如果未定义城市,则输出字符串Unknown City

相关问题