【发布时间】:2021-05-23 14:50:18
【问题描述】:
我有一个 JSON 响应,格式如下:
[
{
"author": 2,
"title": "how to draw",
"slug": "how-to-draw",
"content": "second attempt",
"status": 0,
"date_created": "2020-11-28T20:25:41.650172Z",
"date_posted": "2020-11-28T20:25:41.650172Z",
"tags": "none"
},
{
"author": 1,
"title": "Admin test post",
"slug": "admin-test-post",
"content": "This is just a test of the content field!\r\n\r\nParagraph 2",
"status": 4,
"date_created": "2020-11-16T21:02:02.521705Z",
"date_posted": "2020-11-16T21:37:40.477318Z",
"tags": "a b c"
}
]
我正在努力将响应正确映射到 ReactJS 中的一系列 div。我们的想法是为每个帖子设置一个 div,每个帖子都包含帖子的作者、标题等。我可以使用 post[0].title 来获取数组第一个元素的标题。我错过了什么明显的东西吗?
import React, {useState} from 'react';
import axios from 'axios';
const Django = () => {
const [posts, setPosts] = useState([]);
// proxy set to http://127.0.0.1:8000/
const apiLink = "/api/post/";
const fetchData = async () => {
const res = await axios.get(`${apiLink}`, { headers: { Accept: "application/json"} });
console.log(res.data);
setPosts([res.data]);
}
return (
<div>
<h1>Posts:</h1>
<button onClick={fetchData}>Load jokes</button>
{posts.map((post, key) => {
//console.log(joke);
return (
<div className="data" key={key}>
{post.title}
{key}
</div>
)})}
</div>
);
}
export default Django;
【问题讨论】:
-
您的具体问题是什么?
-
当您使用
setPosts-setPosts([res.data]);时,您将创建一个数组数组。只需直接设置res.data-setPosts(res.data);。 -
嗨,如果我只是映射到 post.title 什么都没有。所以我添加了键作为测试,它只显示 0(数组的第一个键)。所以我不确定我是否没有正确处理 JSON 响应,或者我的地图功能是否不正确?