开发者问题收集

ReactJS API 调用:未处理的拒绝(TypeError):无法读取未定义的属性“map”

2019-02-20
1432

我对 ReactJS 还比较陌生,仍在努力掌握它。我并不是一名专业的前端开发人员,所以我遇到的以下问题可能是 React 开发人员之间的常识,但我找不到任何其他问题直接回答我在这里遇到的问题。

我有一个 API,它显示从数据库中提取的以下类别:

[{
    "category_id": 85,
    "name": "STARTERS",
    "description": "Served with salad & mint sauce",
    "priority": 1
}, {
    "category_id": 86,
    "name": "TANDOORI DISHES",
    "description": "Tandoori dishes are individually marinated in tandoori spices, herbs & yoghurt sauce & cooked in charcoal oven emerging crisp, fragrant & golden red. Served with salad & mint sauce",
    "priority": 2
}, {
    "category_id": 87,
    "name": "TANDOORI MASALA",
    "description": "Special Tandoori Masala",
    "priority": 3
}]

我正尝试通过 ReactJS 项目调用此 API:

import React, { Component } from 'react';

class Api extends React.Component {
constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
  }

  componentDidMount() {
    fetch("https://my-api.com/category")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result.items
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

  render() {
    const { error, isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <ul>
          {items.map(item => (
            <li key={item.category_id}>
              {item.name} {item.description}
            </li>
          ))}
        </ul>
      );
    }
  }
}

export default Api;

我收到的错误如下:

Unhandled Rejection (TypeError): Cannot read property 'map' of undefined

然后它指向渲染方法中上面的以下行:

{item.name} {item.description}

有人能指出我这里错在哪里吗?

谢谢

2个回答

尝试将 items: result.items 更改为 items.result in

(result) => {
  this.setState({
    isLoaded: true,
    items: result.items
  });
},

意思是

应该是

(result) => {
  this.setState({
    isLoaded: true,
    items: result
  });
},
SanjeevMogaBishnoi
2019-02-20

componentDidMount 中的 fetch 是一个 异步 调用,您无需等待响应完全得到解决。

async componentDidMount() {
  const response = await fetch("https://my-api.com/category");
  const json = await response.json();
   this.setState({ items: json });
}
Amir-Mousavi
2019-02-20