【问题标题】:Trying to fetch API via axios, but don't know how to access尝试通过axios获取API,但不知道如何访问
【发布时间】:2021-03-31 14:20:45
【问题描述】:

我尝试从 API 获取一些数据。 API 的格式如下:

[
  {
    "1": {
      "appid": 1,
      "name": "bmw"
    },
    "2": {
      "appid": 2,
      "name": "mercedes"
    },
    "3": {
      "appid": 3,
      "name": "tesla"
    }
  }
]

在反应中我的 app.js 看起来像这样:

import React, { useState, useEffect } from "react";
import axios from "axios";
import ItemsGrid from "./components/items/ItemsGrid";

function App() {
  const [items, setItems] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchItems = async () => {
      const result = await axios({
        url: "http://localhost:3013/items",
        method: "get",
        timeout: 8000,
        headers: {
          "Content-Type": "application/json",
        },
      });

      console.log(result.data);
      setItems(result.data);
      setIsLoading(false);
    };

    fetchItems();
  }, []);

  return (
    <div className="App">
      <ItemsGrid isLoading={isLoading} items={items} />
      <h1>Hello</h1>
    </div>
  );
}

export default App;

还有 ItemsGrid:

import React from "react";

const ItemsGrid = ({ items, isLoading }) => {
  return isLoading ? (
    <h1>Loading...</h1>
  ) : (
    <div>
      {items.map((item) => (
        <h1 key={item.appid}>{item.name}</h1>
      ))}
    </div>
  );
};

export default ItemsGrid;

所以什么都看不到,因为我不知道如何访问数组。在控制台日志中,我看到了一些东西:

[{…}]
0: {1: {…}, 2: {…}, 3: {…}}
length: 1
__proto__: Array(0)

有人知道如何通过映射显示名称吗?

【问题讨论】:

    标签: javascript reactjs api axios fetch-api


    【解决方案1】:

    如果要将带有对象的数组转换为常规数组,可以在数组的第一个元素上使用Object.values

    useEffect(() => {
      const fetchItems = async () => {
        const result = await axios({
          url: "http://localhost:3013/items",
          method: "get",
          timeout: 8000,
          headers: {
            "Content-Type": "application/json",
          },
        });
    
        setItems(Object.values(result.data[0]));
        setIsLoading(false);
      };
    
      fetchItems();
    }, []);
    

    【讨论】:

      【解决方案2】:

      设置项时,可以使用Object#values函数获取返回数据的第一个元素的所有值。

      const fetchItems = async () => {
        ...
        setItems(Object.values(result.data[0]));
        ...
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-19
        • 2020-01-19
        • 1970-01-01
        • 2017-04-27
        相关资源
        最近更新 更多