0

我正在使用文档中的 fetch AJAX 示例并获取以下内容:

 https://learnwebcode.github.io/json-example/animals-1.json

这是 componentDidMount 部分:

componentDidMount() {
fetch("https://learnwebcode.github.io/json-example/animals-1.json")
  .then(res => res.json())
  .then(
    (result) => {
      this.setState({
        isLoaded: true,
        items: result.items
      });
    },

我收到“未捕获的类型错误,无法读取未定义的属性映射”

为什么会这样?这是我第一次尝试使用 fetch API。我试图记录响应对象,但返回未定义。

笔的链接在这里:

 https://codepen.io/damPop/pen/yQLbxV
4

2 回答 2

2

您在渲染方法中遇到错误。

从 中删除项目result.item,因为数据在“结果”中。

像下面

componentDidMount() {
fetch("https://learnwebcode.github.io/json-example/animals-1.json")
  .then(res => res.json())
  .then(
    (result) => {
      this.setState({
        isLoaded: true,
        items: result // remove items, because data is in 'result'
      });
    },
于 2018-11-03T10:17:56.360 回答
2

result 是项目数组,因此 result.items 不存在:

componentDidMount() {
 fetch("https://learnwebcode.github.io/json-example/animals-1.json")
 .then(res => res.json())
 .then(result => {
     console.log(result)
     this.setState({
       isLoaded: true,
       items: result
     });
   })
 .catch(error => {
   this.setState({
     isLoaded: true,
     error
   });
 })
}

https://codepen.io/mThorning/pen/ZmEyao?editors=0010

于 2018-11-03T11:02:52.190 回答