function Shop() {
useEffect(() => {
fetchItems();
}, []);
const [items, setItems] = useState([]);
const fetchItems = async() => {
const data = await fetch('https://fortnite-api.theapinetwork.com/upcoming/get');
const items = await data.json();
console.log(items.data);
setItems(items.data);
};
return (
<div>
{items.map(item => (
<h1>{item.name}</h1>
))}
</div>
);
我无法从API 访问名称元素
*控制台日志中API的快照如下*]1
通过查看数据,数组中的每个元素都有一个名为item
的属性,该属性有一个称为name
的属性
所以你想要
<h1>{item.item.name}</h1>
这将是
return (
<div>
{items.map(item => (
<h1>{item.item.name}</h1>
))}
</div>
);
mapybe可以用作回调参数的不同名称
return (
<div>
{items.map(element => (
<h1>{element.item.name}</h1>
))}
</div>
);
甚至
return (
<div>
{items.map(({item}) => (
<h1>{item.name}</h1>
))}
</div>
);
const fetchItems = async() => {
const res = await fetch('https://fortnite-api.theapinetwork.com/upcoming/get');
const items = await res.json();
return items.data;
};
// testing if items would be what is required
(async() => {
const items = await fetchItems();
const result = items.map(({item}) => item.name);
console.log(result);
})();
答案如下:
import React, { useState, useEffect } from "react";
export default function App() {
useEffect(() => {
fetchItems();
}, []);
const [items, setItems] = useState([]);
const fetchItems = async () => {
const data = await fetch(
"https://fortnite-api.theapinetwork.com/upcoming/get"
);
const items = await data.json();
setItems(items.data);
};
return (
<div>
{items.map((item, i) => (
<h1 key={i}>{item.item.name}</h1>
))}
</div>
);
}
fetch("https://fortnite-api.theapinetwork.com/upcoming/get")
.then((res) => res.json())
.then((data) => {
console.log(data.data[0].item.name)
}
要了解更多见解,请在此处查看我的沙盒:https://codesandbox.io/s/pensive-haibt-i673h?file=/src/App.js:165-327