Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Reactjs和Pokeapi-JSON_Javascript_Reactjs - Fatal编程技术网

Javascript Reactjs和Pokeapi-JSON

Javascript Reactjs和Pokeapi-JSON,javascript,reactjs,Javascript,Reactjs,我不熟悉如何反应和处理JSON,但我在这里读了很多。 所以我一直在尝试将从pokeapi获取的JSON传递到变量中 以下是我到目前为止得到的信息: getPokemons=(id)=> { return fetch(`https://pokeapi.co/api/v2/pokemon/${id}/`) .then(res => { if (res.ok) { //return res.json() conso

我不熟悉如何反应和处理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())


        }
     })
   }
我试过这个方法:
但是不起作用

您需要执行以下操作

     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);
         });
     }

您需要使用
setState
使API结果成为状态的一部分。通过将此组件复制到代码中来尝试此组件:

类PokemonFinder扩展React.Component{
建造师(道具){
超级(道具);
this.state={};
}
getPokemon(id){
取回(`https://pokeapi.co/api/v2/pokemon/${id}/`)
.then(results=>results.json())
。然后(数据=>{
this.setState({data});
});
}
render(){
返回
这是我的国家({
价值:ev.target.value
})}
/>
this.getPokemon(this.state.id)}>getPokemon
{JSON.stringify(this.state.data,null,2)}
;
}
}
ReactDOM.render(,document.getElementById('app'))


这真的很有帮助,谢谢。顺便说一下,如果我要用这个。状态。任何可能的日期都可以,对吗?是的,状态可以存储任何东西。我不知道我做错了什么,但我在使用{JSON.stringify(this.state.data.weight)}时出现了一个类型错误,如果我不使用“data”,则不会显示任何内容!