首页 > 解决方案 > ReactJS 从自定义 API 获取数据并渲染数据

问题描述

我目前正在开发一个 ReactJS 项目,在那里我创建了自己的 JSON-api。我正在尝试获取数组中的特定值,但我得到的只是undefinedconsole.log给了我这个:Array

我的获取功能如下:

_fetchData = async () => {
  const response = await fetch('http://localhost:3000/stories');
  const json = await response.json();

  this.setState({
    title: json.title,
    thumbnail_img_url: json.thumbnail_img_url
  });
}

标签: jsonreactjs

解决方案


请先学习基本编程。

给了我这个:数组。

你自己说json的是一个数组并试图用json.title. 请使用数组的第一个元素或重新访问您的流程并查看您实际想要做什么。

_fetchData = async () => {
  try {
    const response = await fetch('http://localhost:3000/stories');
    const json = await response.json();

    this.setState({
      title: json[0].title,
      thumbnail_img_url: json[0].thumbnail_img_url
    });
  catch (err) { console.error(err.toString()); }
}

推荐阅读