我是React和处理JSON的新手,但是我在这里读了很多东西。 所以我一直试图将我从pokeapi获得的JSON传递给变量 这是到目前为止我得到的:
getPokemons=(id)=> {
return fetch(`https://pokeapi.co/api/v2/pokemon/${id}/`)
.then(res => {
if (res.ok) {
//return res.json()
console.log(res.json())
}
})
}
我尝试了这种方法:Return json object to render method - React.js 但没有用
答案 0 :(得分:2)
您将需要使用setState
使API结果成为状态的一部分。通过将其复制到您的代码中来尝试该组件:
class PokemonFinder extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
getPokemon(id) {
fetch(`https://pokeapi.co/api/v2/pokemon/${id}/`)
.then(results => results.json())
.then(data => {
this.setState({data});
});
}
render() {
return <div>
<input value={this.state.id}
onChange={(ev) => this.setState({
value: ev.target.value
})}
/>
<button onClick={() => this.getPokemon(this.state.id)}>Get Pokemon</button>
<div>{JSON.stringify(this.state.data, null, 2)}</div>
</div>;
}
}
ReactDOM.render(<PokemonFinder/>, document.getElementById('app'));
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
答案 1 :(得分:1)
您需要执行以下操作
getPokemons=(id)=> {
fetch(`https://pokeapi.co/api/v2/pokemon/${id}/`)
.then(res => res.json())
.then(data => {
this.setState({data}); //here you are setting data to data state variable
})
.catch(err => {
console.log(err);
});
}