从Axios请求中获取数据

时间:2019-10-15 14:35:15

标签: 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的操作时,我没有得到返回的值,它将返回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发送到我的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}/>

 ));

1 个答案:

答案 0 :(得分:1)

您需要像这样将数据发送到组件:

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;

相关问题