javascript - 从axios请求获取数据

标签 javascript reactjs axios

我有一个返回以下数据的 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.commentbodydata[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/

相关文章:

javascript - 使用多个标签过滤内容,但一次只允许用户选择一个标签

javascript - 日期字符串格式

Django React 项目结构

javascript - 找不到模块 : Can't resolve 'moment' in 'node_modules\react-moment\dist' in reactjs

javascript - 如何同时调用两个不同的 REST api 端点并在应用程序的一个端点上显示来自这两个端点的数据?

重定向后未加载 JavaScript 文件?

javascript - 当一些滑动解锁时我如何将它发送到特定链接

reactjs - 如何正确分配 axios 响应以响应函数组件状态

javascript - 为什么我的网页在 NodeJS POST 请求后刷新?

reactjs - 带有 fetch api 的 React hook