0

我正在尝试从 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};
4

3 回答 3

1

如果这是一个 React 应用程序,那么你想在componentDidMount. Axios 会自动返回一个 Promise。

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;

这样做会在 React 应用程序加载并设置组件状态的 JSON 数据后发送 Axios 请求。您应该能够通过this.state.data.

使用有效的 API 调用查看这个Codepen 示例

于 2020-03-26T23:02:12.837 回答
0

好吧,首先,我建议您阅读有关承诺的内容。实现您需要的一个好方法是使用 async/await 语法检查以下代码:

const axios = require('axios');

const getPokemon = async () => {
    try{
       let res = await axios.get('https://pokeapi.co/api/v2/pokemon/');
       return res.data.results;
    }
    catch(error){
      return null //that's what you did in your code.
    }
}

export {getPokemon};
于 2020-03-26T23:03:27.760 回答
0
  1. 删除“.result”
const axios = require("axios");
    
const getPokemon = async () => {
   try {
      let res = await axios.get("https://jsonplaceholder.typicode.com/users");
      return res.data; **here remove his .result**
   } catch (error) {
      return null; //that's what you did in your code.
   }
};
    
export default getPokemon;
  1. 在 index.js 或任何页面中调用它:
import getPokemon from "./GetPokimon";
const xyz = async () => {
   const data = await getPokemon();
   alert(JSON.stringify(data));//u will see the data here
}
xyz(); //calling getPokemon()
于 2022-03-04T20:59:19.243 回答