我尝试从 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/