![](/img/trans.png)
[英]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.