我正在消费 pokeapi对于一个个人项目,想边做边学 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
我只想渲染这个 pokemon 对象。这就是我现在正在做的方式:
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.
有没有办法在表格中渲染这个对象?我想这不会在状态中保存数据,但我不知道该怎么做。
最佳答案
您不能直接在 React 中打印对象或数组。虽然 {JSON.stringify(this.state.pokemon)}
绝对有效并允许您将对象打印为字符串,但如果需要,您也可以单独打印对象属性。
您可以通过将 {this.state.pokemon}
更改为类似以下内容来修复您的代码-
{this.state.pokemon.id}
{this.state.pokemon.name}
{this.state.pokemon.sprite}
{this.state.pokemon.height}
{this.state.pokemon.weight}
{this.state.pokemon.types}
关于javascript - 将 json 对象返回给渲染方法 - React.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51326921/