[英]React, typescript - Argument of type 'string | null' is not assignable to parameter of type 'string'
[英]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.