【问题标题】:How to access to the data of the async response with axios? [duplicate]如何使用 axios 访问异步响应的数据? [复制]
【发布时间】:2023-02-11 03:06:52
【问题描述】:

我正在使用 React 和 TypeScript 开发一个应用程序,我的服务文件中有这个服务getData()

export const getData = async (): Promise<ItemModel> => {
  const { data } = await axios.get("/db/data.json");
  console.log("response", data);
  return data;
};

console.log() 产生了我所期望的,这意味着:

然而,当我在我的功能组件上使用这个方法getData()时,只是为了检查它是否正常工作:

export const App = () => {
  const data = getData();
  console.log("data0", data[0]);
  console.log("data1", data[1]);

我有以下结果:

所以,基本上,我有一个只适用于服务文件的服务,当尝试在功能组件上使用时,它给我 undefined。错误在哪里?我知道 getData 是异步的,我想如果我在方法中使用 async/await 应该足以在响应到达时返回数据给我,而不是之前。但是,然而,还不够。错误在哪里?多谢 :)

【问题讨论】:

    标签: reactjs typescript asynchronous async-await axios


    【解决方案1】:

    你需要用 useEffect 包装你的 fetch

    useEffect(() => {
      const fetchData = async () => {
        const data = await getData();
        console.log("data 0", data[0]);
      };
      fetchData();
    }, []);
    

    【讨论】:

    • 使用 useEffect console.log() 也是未定义的: export const App = () => { useEffect(() => { const data = getData(); console.log("data0", data[0]); console.log("data1", data[1]); }, []);
    • 我更新了答案,应该可以
    【解决方案2】:

    你的 getData() 函数应该返回一个 Promise 但你返回的是 data 对象。我更惊讶你没有得到任何错误。

    尝试返回 Promise,因为它是您函数的签名。像这样:

    function getData():Promise<ItemModel>  {
      return new Promise<ItemModel)(async(inResolve, inReject)=>{
         try{
           return inResolve(await axios.get("/db/data.json").data);
         }
         catch(exception:any) return inReject(exception)
      })
       
    }
    

    然后,您必须在调用它时解决 getData() 的承诺。使用 then().cacth() 或使用 async await catch。像这样:

    function SomeComponent() {
      const [data, setData] = useState(new Array());
      useEffect(async()=> {
        try {
         setData(await getData());
        }
        catch(exception) {
          /***handle exception here***/
        }
    
       }, [])
    }
    

    我还没有测试这段代码,如果有任何错误,我们深表歉意。但我只是想从整体上说明我的想法

    【讨论】:

      猜你喜欢
      • 2018-12-24
      • 1970-01-01
      • 2023-03-12
      • 2021-05-05
      • 2019-07-25
      • 2020-12-09
      • 2015-01-20
      • 1970-01-01
      • 2020-12-15
      相关资源
      最近更新 更多