javascript 如何使用Axios和React js从API中获取特定数据?

myzjeezk  于 2023-05-27  发布在  Java
关注(0)|答案(1)|浏览(153)

-1
嗨,我是ReactJS的新手,我想从Instagram的图形api中获取一个带有特定文本的图片。例如,如果图片的标题在Instagram中有“是”字,那么必须在主页中显示。我试图用const myPost =包含yes字来定义Mypost,但我没有得到任何回报。谢谢你的帮助。

import React,{useState} from 'react'
import axios from 'axios';
import ReactDOM from "react-dom";

function Deneme() {
    // component variables go here
    const [Posts, setPosts] = useState(null);
  
    const fetchData = async () => {
      const response = await axios.get(`https://graph.instagram.com/me/media?fields=id,caption,media_url,permalink,username&access_token=IGQV....`)

  
      setPosts(response.data.data) 
    };

    return (
      <div className="Deneme">
        <h1>Game of Thrones Posts</h1>
        <h2>Fetch a list from an API and display it</h2>
  
        {/* Fetch data from API */}
        <div>
          <button className="fetch-button" onClick={fetchData}>
            Fetch Data
          </button>
          <br />
        </div>
  
        {/* Display data from API */}
        <div className="Posts">
          {Posts &&
            Posts.map((posts, index) => {
              const myPost = posts.caption.contains("yes"); 
              const cleanedDate = new Date(posts.released).toDateString();
              console.log(cleanedDate)
  
              return (
                <div className="posts" key={index}>
                  <h3>posts {index + 1}</h3>
                  <h2>{myPost.username}</h2>
  
                  <div className="details">
                    <p>{myPost.caption} </p>
                    <img className="post_img"  src={myPost.media_url} alt="image"/>
                  </div>
                </div>
              );
            })}
        </div>
      </div>
    );
  }
  export default Deneme
2lpgd968

2lpgd9681#

您没有在任何地方调用fetchData函数。当组件第一次使用useEffect钩子呈现时调用它:

useEffect(() => {
   fetchData();
}, []);

更多useEffect:https://reactjs.org/docs/hooks-effect.html

相关问题