我试图在使用ReactJS时从具有嵌套对象的API(Magic the Gathring Scryfall API)中获取数据。一旦尝试使用嵌套对象中的数据,就会收到“无法读取未定义的png”的信息。我发现这可能是一个异步问题,并通过将初始数组的状态更改为null,然后在渲染器中添加了if语句来解决了这个问题,但我将API网址从https://api.scryfall.com/cards?page=3更改为{ {3}},尽管我收到了与第一个URL相同格式的JSON,但我无法再访问嵌套对象中的图像url。我现在很茫然。
我尝试使用axios,然后尝试将获取操作放入一个单独的函数中,然后将该功能放入componentDidMount中,但是没有运气。将'cards'设置为null,然后将“ if(cards === null){return null;}放入渲染器中对第一个链接有效,但对第二个链接无效。
import React,{Component} from 'react';
import logo from './logo.svg';
import './App.css';
import Login from './components/Login'
class App extends Component {
constructor() {
super()
this.state = {
cards: null,
isUpdated:false
}
}
componentDidMount() {
this.populateCards()
}
populateCards() {
let url = 'https://api.scryfall.com/cards/search?order=cmc&q=c%3Ared+pow%3D3 '
fetch(url)
.then(response => response.json())
.then(json => {
console.log("setting the state.")
console.log(json.data)
this.setState({cards: json.data})
})
}
render() {
const { cards } = this.state;
if (cards === null) {
return null;
}
let cards1 = this.state.cards
let cardItems = cards1.map((card) => {
return (
<li>{card.name} - {card.id}
<p></p><img src={card.image_uris.png}/></li>
)
})
return (
<div className="App">
<h1>HOME PAGE</h1>
<Login />
<ul>
{cardItems}
</ul>
</div>
)
}
}
export default App;
仅需弄清楚此JSON发生了什么,然后我才能继续编写一些搜索框。非常感谢可以提供的任何帮助。
返回的JSON如下所示:
{
"object": "list",
"total_cards": 248583,
"has_more": true,
"next_page": "https://api.scryfall.com/cards?page=4",
"data": [
{
"object": "card",
"id": "18794d78-5aae-42de-a45b-3289624689f1",
"oracle_id": "a6543f71-0326-4e1f-b58f-9ce325d5d036",
"multiverse_ids": [
463813
],
"name": "Gateway Plaza",
"printed_name": "門前廣場",
"lang": "zht",
"released_at": "2019-05-03",
"uri": "https://api.scryfall.com/cards/18794d78-5aae-42de-a45b-3289624689f1",
"scryfall_uri": "https://scryfall.com/card/war/246/zht/%E9%96%80%E5%89%8D%E5%BB%A3%E5%A0%B4?utm_source=api",
"layout": "normal",
"highres_image": false,
"image_uris": {
"small": "https://img.scryfall.com/cards/small/front/1/8/18794d78-5aae-42de-a45b-3289624689f1.jpg?1556241680",
"normal": "https://img.scryfall.com/cards/normal/front/1/8/18794d78-5aae-42de-a45b-3289624689f1.jpg?1556241680",
"large": "https://img.scryfall.com/cards/large/front/1/8/18794d78-5aae-42de-a45b-3289624689f1.jpg?1556241680",
"png": "https://img.scryfall.com/cards/png/front/1/8/18794d78-5aae-42de-a45b-3289624689f1.png?1556241680",
"art_crop": "https://img.scryfall.com/cards/art_crop/front/1/8/18794d78-5aae-42de-a45b-3289624689f1.jpg?1556241680",
"border_crop": "https://img.scryfall.com/cards/border_crop/front/1/8/18794d78-5aae-42de-a45b-3289624689f1.jpg?1556241680"
},
"mana_cost": "",
"cmc": 0,
答案 0 :(得分:1)
响应中的某些对象没有image_uris
属性,因此会引发错误。
添加这些行
let filtered = cards1.filter(card => card.image_uris);
然后映射到过滤后的数组,您将获得所需的内容
let cardItems = filtered.map(card => {
return (
<li>
<img src={card.image_uris.png}/>
</li>
);
});