gpt4 book ai didi

javascript - Reactjs 和 Pokeapi JSON

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

我是 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 但没用

最佳答案

您需要使用 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>

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

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