Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/438.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 从Axios返回数据_Javascript_Ecmascript 6_Promise_Axios_Es6 Promise - Fatal编程技术网

Javascript 从Axios返回数据

Javascript 从Axios返回数据,javascript,ecmascript-6,promise,axios,es6-promise,Javascript,Ecmascript 6,Promise,Axios,Es6 Promise,我正在尝试从axios API调用返回响应。我不太明白什么是承诺,我找到的所有教程/信息都只记录了响应,我想返回 这就是我所拥有的,但是当我调用getPokemon时,它是未定义的 const axios = require('axios'); const getPokemon = () => { axios.get('https://pokeapi.co/api/v2/pokemon/') .then(function (response) { cons

我正在尝试从axios API调用返回响应。我不太明白什么是承诺,我找到的所有教程/信息都只记录了响应,我想返回

这就是我所拥有的,但是当我调用getPokemon时,它是未定义的

const axios = require('axios');

const getPokemon = () => {
    axios.get('https://pokeapi.co/api/v2/pokemon/')
    .then(function (response) {
        console.log("Response:", response.data.results);
        return response.data.results;
    })
    .catch(function (error) {
        return null;
    });
}

export {getPokemon};

如果这是React应用程序,那么您需要在
componentDidMount
中调用Axios。Axios自动返回承诺

class Example extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: ""
    };
  }

  componentDidMount() {
    axios
      .get("https://pokeapi.co/api/v2/pokemon/")
      .then(res => {
        console.log(res);
        this.setState({
          data: res.data.results
        });
      })
      .catch(err => {
        console.log(err);
      });
  }
  render() {
    let pokemon = this.state.data;
    let display = Object.values(pokemon).map((item, key) => {
      return (
        <div>
          <p>{item.name}</p>
          <p>{item.url}</p>
        </div>
      );
    });

    return (
    <div>{display}</div>
    );
  }
}

export default Example;
类示例扩展组件{
建造师(道具){
超级(道具);
此.state={
数据:“”
};
}
componentDidMount(){
axios
.get(“https://pokeapi.co/api/v2/pokemon/")
。然后(res=>{
控制台日志(res);
这是我的国家({
数据:res.data.results
});
})
.catch(错误=>{
控制台日志(err);
});
}
render(){
让pokemon=this.state.data;
让显示=对象.值(口袋妖怪).map((项目,键)=>{
返回(
{item.name}

{item.url}

); }); 返回( {display} ); } } 导出默认示例;
这样做将在React应用程序加载并将JSON数据设置为组件状态后发送Axios请求。您应该能够通过
this.state.data
访问JSON数据


看看这个。

好吧,首先,我建议你读一下承诺。 实现所需功能的一个好方法是使用async/await语法检查以下代码:

const axios=require('axios');
const getPokemon=async()=>{
试一试{
让res=等待axios.get('https://pokeapi.co/api/v2/pokemon/');
返回res.data.results;
}
捕获(错误){
return null//这就是您在代码中所做的。
}
}
导出{getPokemon};

如果您不理解承诺,那么使用axios将非常具有挑战性。从……开始。但是getPokemon并没有返回任何东西,不管是承诺还是其他。使用任何一种语法都不是一种很好的阅读方法。“这就是您在代码中所做的”-不,在成功和失败案例中,他们返回
未定义的