如何使用 axios 在 React 中设置数据?

how to set data in React with axios?

如何在 <h1> 标签中显示名称和 ID。该项目通过 axios 从 API.

获取数据
import React, { useState } from "react";
import axios from "axios";

const Details = () => {

  const [data, setData] = useState({
    name: "",
    id: "",
  });

  const apiDetails = () => {
    axios
      .get(`https://api.coingecko.com/api/v3/coins/${"ethereum"}`)
      .then((response) => {
        // console.log(response);
        setData({
          name: response.data.name,
          id: response.data.id,
        });
        return setData;
      });
  };

  return (
    <div>
      <h1>{setData.name}</h1>
      <h1>{data.name}</h1>
      <h1>{setData.id}</h1>
      <h1>{data.id}</h1>
      <h1>{setData.name}</h1>
    </div>
  );
};

export default Details;

你应该这样使用useEffect,你可以了解更多关于这个钩子的信息here

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

const Details = () => {

  const [data, setData] = useState(null);

  const apiDetails = () => {
    axios
      .get(`https://api.coingecko.com/api/v3/coins/${"ethereum"}`)
      .then((response) => {
        // console.log(response);
        //setData({
        //  name: response.data.name,
        //  id: response.data.id,
        // });
        return response;
      });
  };

 useEffect(() => {  
  (async () => {
   const response = await apiDetails(); 
   setData({
      name: response.data.name,
      id: response.data.id,
    });
  })();
 }, [])

  if (data) {
   return (
      <>  
       <h1>{data.name}</h1>
       <h1>{data.id}</h1>
      </>     
   );
  }  

  return null;  
};

export default Details;