从 React.js 中的 json 文件中获取数据

新手上路,请多包涵

我有一个 json 文件调用 data.json 例如(我使用 React.js):

 [{"id": 1,"title": "Child Bride"},
{"id": 2, "title": "Last Time I Committed Suicide, The"},
{"id": 3, "title": "Jerry Seinfeld: 'I'm Telling You for the Last Time'"},
{"id": 4, "title": "Youth Without Youth"},
{"id": 5, "title": "Happy Here and Now"},
{"id": 6, "title": "Wedding in Blood (Noces rouges, Les)"},
{"id": 7, "title": "Vampire in Venice (Nosferatu a Venezia) (Nosferatu in Venice)"},
{"id": 8, "title": "Monty Python's The Meaning of Life"},
{"id": 9, "title": "Awakening, The"},
{"id": 10, "title": "Trip, The"}]

我是我的 componentDidMount 我有以下内容:

       fetch('./data/data.json')
.then((response) => response.json())
.then((findresponse)=>{
  console.log(findresponse.title)
  this.setState({
    data:findresponse.title,
  })
})

}

在我的渲染中:

  <ul>

         <li>        {this.state.title}</li>;

    </ul>

我想列出我的 json 文件中的所有标题,

否则它说 .then((response) => response.json()) 是一个匿名函数。 . .

如何解决这个问题?我有点困惑

非常感谢

原文由 tibewww 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 573
2 个回答

您的响应不是具有 title 属性的对象,而是一个对象数组,所有对象都具有 title 属性。

 this.setState({ data: findresponse });

然后在你的渲染中

<ul>
  {this.state.data.map((x, i) => <li key={i}>x.title</li>)}
</ul>

原文由 Jared Smith 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用异步/等待。它需要更少的代码行。

 async getData(){
   const res = await fetch('./data/data.json');
   const data = await res.json();
   return this.setState({data});
}

在 componentDidMount() 中调用函数即

componentDidMount(){
   this.getData();
}

最后,在渲染中,映射数据数组

render (){
   return {<ul>{this.state.data.map(item => <li>{item.title}</li>)} </ul>
)
}

原文由 Rilwan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题