簡體   English   中英

NextJs 中的 axios 響應中的類型“never”.ts(2339) 上不存在屬性

[英]Property does not exist on type 'never'.ts(2339) in axios response in NextJs

我正在做一個 NextJs 項目,我對 NextJs 很陌生。 我在使用 Axios 時遇到了問題。 我正在使用 VS 代碼並試圖訪問(response.data.sliders),但我的編輯器顯示錯誤。 錯誤是“'never'.ts(2339) 類型上不存在屬性'滑塊'”。 但是在執行了 console.log(response.data) 之后,我可以清楚地看到那里的“滑塊”。 我正在獲取滑塊數據,但 vs 代碼顯示錯誤。 我對此感到非常沮喪,但突然間,當我想在這里問一個關於我的問題的問題時,我得到了解決方案,它對我來說神奇地起作用了! 所以我想為什么不寫下這個問題的解決方案,以便像我這樣的其他人可以從中獲得幫助。 我將附上我的項目的屏幕截圖和一個小代碼片段,以便您清楚地了解我的問題。 這是 console.log(response.data) 的結果

這是我的代碼。

 import axios from "axios"; const IndexPage = (props) => { return ( <main> <Section1 Section1Props={props.Section1Props} /> </main> ); }; export async function getServerSideProps(context) { try { const response = await axios.get(urlGenerator("api/v1/frontend-configuration")); const data = await response.data; return { props: { Section1Props : data.sliders, // here I was getting the error for 'sliders' }, } } catch (error) { console.log(error); } } export default IndexPage;

最后我發現問題出在我的 axios import 語句中。 我需要像這樣導入 axios -

const { default: axios } = require('axios'); // or
const axios = require('axios').default;

而不是這個 -

import axios from "axios";

我不知道為什么它起作用了。 我仍然感到很高興,希望它也對你有所幫助。 如果您知道它為什么起作用,請在此處解釋。 這對我理解整個事情會有幫助。

我通過如下聲明響應變量解決了我的問題

const responseTest: AxiosResponse<any>  = await axios.get('https://api.github.com/users/maths032')
    
    
  alert(responseTest.data.id)

並按如下方式導入 axios

import axios, { AxiosResponse } from "axios";

我不知道這是否是最好的方法,但它對我有用。

來自 axios 文檔

為了在使用帶有 require() 的 CommonJS 導入時獲得 TypeScript 類型(用於智能感知/自動完成),請使用以下方法:

 const axios = require('axios').default; // axios.<method> will now provide autocomplete and parameter typings

我需要一個 ESM 導入,所以下面是我的做法:

import axios, { AxiosResponse, AxiosError } from 'axios';
const Axios = axios.default;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM