【问题标题】:how to set data in React with axios?如何使用 axios 在 React 中设置数据?
【发布时间】:2022-01-14 19:30:15
【问题描述】:

应该如何在<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;

【问题讨论】:

    标签: javascript reactjs ajax axios react-bootstrap


    【解决方案1】:

    你应该使用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;
    

    【讨论】:

    • 谢谢,没关系这个错误出现在控制台选项卡中:Details.jsx:27 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'data') at Details.jsx:27:1 就是这个
    • 请查看我的更新,因此必须检查数据是否不为空,我所做的另一项更改是将您的state 初始化为空。
    猜你喜欢
    • 2017-06-12
    • 2020-11-21
    • 2021-07-20
    • 1970-01-01
    • 2021-07-04
    • 2019-12-21
    • 1970-01-01
    • 2022-01-02
    • 2021-07-18
    相关资源
    最近更新 更多