json - ReactJS 从自定义 API 获取数据并渲染数据
问题描述
我目前正在开发一个 ReactJS 项目,在那里我创建了自己的 JSON-api。我正在尝试获取数组中的特定值,但我得到的只是undefined
,console.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
});
}
解决方案
请先学习基本编程。
给了我这个:数组。
你自己说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()); }
}
推荐阅读
- visual-studio-code - vscode 可以更新导入移动文件而不是移动文件的文件的导入路径吗?
- scala - 使用 ScalaTest 3.0 生成 html 报告
- c# - 如何在 ASP.NET Core 中使用 OnActionExecutionAsync
- r - lm()-function 在 SolusOS Linux 上的结果与在 Windows 上的结果不同
- node.js - 如何在猫鼬中设置参考文档_id可选?
- c++ - 用于插入操作的二叉搜索树代码问题
- sql - XML 值的 SQL Server Where 子句路径
- r - 带有插入符号的自定义模型(R6 类)给出绑定错误
- python - 在 slurm 上安排数组作业时使用 argparse?
- python - “自我”如何正确更新原始变量?N皇后问题中的递归/回溯(Python)