繁体   English   中英

从 Axios 请求中获取数据

[英]Get data from Axios request

我有一个返回以下数据的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 之类的操作时,我没有得到返回的值,它返回undefined 请帮忙,下面是我的axios request

  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发送给我的反应组件

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM