簡體   English   中英

React Typescript - 'string' 類型的參數不可分配給 useState 中的類型參數

[英]React Typescript - Argument of type 'string' is not assignable to parameter of type within useState

我有一個 React web 應用程序我想拉入兩個包含 API 數據的 URL 並顯示所述數據。 一個 URL 是英語,一個是法語。

拉入法語 API 數據,我需要將 append "?accept-language=fr-ca" 到原始英語 URL 的末尾:

let param = "?";
let french = param + "accept-language=fr-ca";

然后在使用 setData 時:

setData(response.data + french);

french附加到上面的setData時,我收到以下 TypeScript 錯誤:

Argument of type 'string' is not assignable to parameter of type 'SetStateAction<InspectionReportData[] | null | undefined>'.

如何修復此 TypeScript 錯誤?

完整代碼如下:

interface Props_PIReport {
  lang: string;
  jsonDataProduct: Type_jsonModelDetails | undefined;
}

const PeriodicAnnualInspectionReport = ({
  lang,
  jsonDataProduct,
}: Props_PIReport) => {
  // Make a call to fetch the inspection report data within the original API
  const [data, setData] = useState<InspectionReportData[] | null>();

  useEffect(() => {
    let param = "?";
    let french = param + "accept-language=fr-ca";
    if (lang === "fr") {
      if (jsonDataProduct) {
        axios.get(jsonDataProduct["inspection-link"]).then((response) => {
          setData(response.data + french);
        });
      }
    } else {
      ...
    }
  }, []);

return (
    ...
  );
};

您沒有使用正確類型的參數調用setData

useState<InspectionReportData[] | null>()

此行意味着您將使用以下兩種類型之一調用setState :null 或InspectionReportData數組。

您實際上是用字符串類型調用它: setData(response.data + french);

你需要要么讓它接受一個字符串,要么改變你調用它的方式。

這正是錯誤消息的含義。

暫無
暫無

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

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