我正在消费pokeapi https://pokeapi.co/对于一个个人项目,并且想在做的同时学习 React。一旦成功从 api 检索到所需信息,如下所示:
handleSubmit(event) {
axios.get('https://pokeapi.co/api/v2/pokemon/' + this.state.input_id).then(r => {
var data = r.data;
var types = [];
for (let i = 0; i < data.types.length; i++) types.push(data.types[i].name);
const pokemon = {
id: data.id,
name: data.name,
sprite: data.sprites.front_default,
height: data.height,
weight: data.weight,
types: types,
};
this.setState({
pokemon: pokemon
});
}).catch(e => {
console.log(e);
}); // axios
event.preventDefault();
} // handleSubmit
我想要的只是渲染这个神奇宝贝对象。这就是我现在正在做的方式:
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Pokemon's id
<input type="text" value={this.state.input_id} onChange={this.handleChange} />
</label>
<input type="submit" value="Find!"/>
</form>
<code>{this.state.pokemon}</code>
</div>
);
} // render
当然,这会引发下一个错误:
Objects are not valid as a React child (found: object with keys {id, name, sprite, height, weight, types}). If you meant to render a collection of children, use an array instead.
有没有办法在表格内渲染这个对象?我想这不会在状态内保存数据,但我不知道该怎么做。