我有一个返回以下数据的 api
[{…}]
0: {id: 1, postId: 86, commentBody: "This is a test comment", giphyUrl: "https://media2.giphy.com/",
postPicture: "pic.com", …}
length: 1
__proto__: Array(0)
[{"id":1,"postId":86,"commentBody":"This is a test comment","giphyUrl":"https://media2.giphy.com/","postPicture":"pic.com","userId":1,"userIdto":2,"userIdName":"Elton","userIdtoName":null}]
我想访问评论正文,但是当我执行 data.commentbody
或 data[0]
.commentbody 之类的操作时,我没有得到返回的值,它返回 未定义
。请帮忙,下面是我的 axios 请求
。
const fetchComments = async (id) => {
try {
return await axios.get('http://10.6.254.22:5000/comments/' + id)
} catch (error) {
console.error(error)
}
}
const comments = async(id) => {
const fetchedComments = await fetchComments(id);
console.log(fetchedComments.data)
// console.log(fetchedComments.data.message)
return fetchedComments.data
}
然后我想将它作为 prop
发送到我的 React 组件
const reversedProps = this.props.posts.reverse();
const postItems = reversedProps.map(post => (
console.log('post id is===' + post.id),
comments(post.id),
<PostBodyTemplate key={post.id} title={post.title} postBody={post.postBody} giphyUrl =
{post.giphyUrl} userWhoPosted={post.userIdName}/>
));
最佳答案
您需要将数据发送到组件,如下所示:
comments.map(comment => {
return <PostBodyTemplate key={post.id} comment={comment} />;
});
更完整的示例:
import React, { useState, useEffect } from "react";
function App() {
const [comments, setComments] = useState([]);
useEffect(() => {
const getComments = async () => {
const response = await axios.get("http://10.6.254.22:5000/comments/1");
setComments(response.data);
};
getComments();
}, []);
return (
<div>
{comments.map(comment => {
console.log(comment.commentBody); // => you can access the commentBody like this
return <PostBodyTemplate key={post.id} comment={comment} />;
})}
</div>
);
}
export default App;
关于javascript - 从axios请求获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58397092/