gpt4 book ai didi

javascript - 试图通过 axios 获取 API,但不知道如何访问

转载 作者:行者123 更新时间:2023-12-04 08:23:07 25 4
gpt4 key购买 nike

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

[
{
"1": {
"appid": 1,
"name": "bmw"
},
"2": {
"appid": 2,
"name": "mercedes"
},
"3": {
"appid": 3,
"name": "tesla"
}
}
]
在 react 中,我的 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)
任何人都知道如何通过映射显示名称?

最佳答案

如果要将带有对象的数组转换为常规数组,可以使用 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();
}, []);

关于javascript - 试图通过 axios 获取 API,但不知道如何访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65399223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com