【问题标题】:Axios not fetching data using ReactjsAxios 不使用 Reactjs 获取数据
【发布时间】:2023-02-01 12:37:52
【问题描述】:

我正在使用 Reactjs/nextjs,我正在尝试使用“Axios”获取数据,在“Api url”中,数据正在获取/显示,但在我的网页中显示“还没有记录”,我哪里错了?这是我当前的代码

import React from 'react'
import { useEffect, useState } from "react";
import axios from 'axios';


function Displaydata() {
      const [posts,setPosts]=useState([]);

useEffect(()=>
{
    const getdata=async()=>
    {
        const { data: res } = await axios.get(
            "xxxxxxxxxxxxxxxxxxxx/api/Allvideo"
          );
          console.log(res);
          setPosts(res);
    };
})
return(
    <div>
        {posts?.length ? posts.map((product: { id: any; link: any; }) => <p key={product.id}>
        {product.id}-{product.link}</p>) 
            : <h3>There are no records yet</h3>}
            </div>
    )
}

export default Displaydata

【问题讨论】:

  • 我在代码中没有看到任何 getData 调用。

标签: javascript reactjs next.js


【解决方案1】:

我们需要将 useEffect 的第二个参数作为空数组或值数组传递。然后 getdata 函数声明但未调用。请找到以下代码。

useEffect(() => { 
  const getdata = async() => {
    const { data: res } = await axios.get("xxxxxxxxxxxxxxxxxxxx/api/Allvideo");
      console.log(res);
      setPosts(res);
   };
   getdata();
 }, []);

希望这可以帮助!!!

【讨论】:

    猜你喜欢
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 2020-09-21
    • 1970-01-01
    相关资源
    最近更新 更多