gpt4 book ai didi

javascript - Reactjs 与 Pokeapi

转载 作者:行者123 更新时间:2023-11-30 15:41:07 31 4
gpt4 key购买 nike

我有一个应用程序可以搜索宠物小 Sprite 的名称并读取数据,例如。姓名、高度、体重。现在说到能力,我无法理解能力名称的值(value)。

这是我的 app.js

import React, { Component } from 'react';
import './App.css';
import Request from 'superagent';

class App extends Component {
constructor(props) {
super(props);
this.state = {
body: "",
value: "",
name: "",
abilities: "",
order: "",
weight: "",
height: ""
};

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}

handleChange(event) {
this.setState({value: event.target.value.toLowerCase()});
}

handleSubmit(event) {
var url = "https://pokeapi.co/api/v2/pokemon/"+this.state.value;
Request.get(url).then((response) => {
this.setState({
body: response.body,
height: response.body.height,
weight: response.body.weight,
abilities: response.body.abilities,
name: response.body.name,
order: response.body.order,
picFront: response.body.sprites.front_default,
picBack: response.body.sprites.back_default,
picShiny: response.body.sprites.front_shiny,


});
});
event.preventDefault();
}

render() {

return (
<div className="flex">
<div className="App">
<h1>Search Pokemon</h1>
<form onSubmit={this.handleSubmit}>
<input type="text" value={this.state.value} onChange={this.handleChange} />
<input type="submit" value="Submit" />
</form>
</div>
<div className="app2">
<h1><small>{this.state.order} </small>{this.state.name}</h1>
<img alt={this.state.name} src={this.state.picFront}/>
<img alt={this.state.name} src={this.state.picBack}/>
<img alt={this.state.name} src={this.state.picShiny}/>
<p>Height: {this.state.height}</p>
<p>Weight: {this.state.weight}</p>
<p>list of abilities here</p>
</div>
</div>

);
}
};


export default App;

最佳答案

能力具有这种结构。您可以通过记录 this.state.abilities 来检查这一点

abilities: [
{
slot: 3,
is_hidden: true,
ability: {
url: "https://pokeapi.co/api/v2/ability/31/",
name: "lightning-rod"
}
},
{
slot: 1,
is_hidden: false,
ability: {
url: "https://pokeapi.co/api/v2/ability/9/",
name: "static"
}
}
]

它只是一个数组。您需要做的是迭代此数组以检索这些名称值。有很多方法可以做到这一点,但一般逻辑应该是这样的:

“对于 abilities 数组中的每个对象,我需要检索 ability.name”

我将在此处发布一些代码,但在查看我的代码之前尝试自己解决它。

在你的p标签中,你可以这样做

    <p>
list of abilities here:
{this.state.abilities && this.state.abilities.map((abilityObject) =>
abilityObject.ability.name).join(', ')}
</p>

关于javascript - Reactjs 与 Pokeapi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40797523/

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