【问题标题】:axios not getting any response?axios 没有得到任何回应?
【发布时间】:2022-11-22 09:54:15
【问题描述】:

我无法通过简单的 axios.get 调用获得响应,尽管仍然没有检索到任何数组作为响应

import { React, useEffect, useState } from "react";
import axios from "axios";
import List from "./List";

const url = "https://api.coingecko.com/api/v3/search";

export default function SearchField() {
  const [query, setQuery] = useState("");
  const [retrievedData, setRetrievedData] = useState("");

  useEffect(() => {
    const {
      config,
    } = async () => {
      await axios
        .get(
          url,
          { params: { query: "bitcoin" } },
          { headers: { Accpet: "Application/json" } }
        )
        .then(console.log(config));
    };
  }, []);

  return (
    <section>
      <input
        placeholder="search"
        name="search"
        onChange={(e) => setQuery(e.target.value)}
      />
    </section>
  );
}

我想记录 config 的值并将其保存在 retrievedData 状态。

【问题讨论】:

  • headers 中正确拼写accept 是否为您解决了问题?
  • 不幸的是不,那是我之前重写的错字
  • .then() 接受一个函数,但 console.log() 返回 undefined。请试试.then(({ data }) =&gt; data)。另外,paramsheaders 应该在同一个对象中

标签: reactjs axios


【解决方案1】:

这应该让你工作。您实际上并没有在任何地方返回或使用来自 fetch 的数据,只是记录它。


const getData = async () => {
  const bitcoinData = await axios.get(url,
    {
      params: { query: "bitcoin" },
      headers: { Accept: "application/json" }
    }
  )
  console.log(bitcoinData)
  setRetrievedData(bitcoinData)
}

useEffect(() => {
  getData()
}, [])

【讨论】:

  • Axios 承诺使用 Response 对象解析
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 2018-06-18
  • 2015-03-28
  • 2020-08-16
  • 2023-02-23
  • 1970-01-01
相关资源
最近更新 更多