import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useMount, useAsyncFn } from 'react-use';
import { Grid } from '@material-ui/core';
import { useTranslation } from 'react-i18next';
import LegalEntitiesService from 'shared/services/LegalEntitiesService';
import { TextField } from 'shared/components/Form';
const LegalEnityInformation: React.FC= () => {
const { legalEntityId } = useParams();
const { t } = useTranslation();
const [legalEntity, setLegalEntity] = useState<any>({
id: null,
name: '',
address: '',
municipalityCode: '',
eik: '',
municipality: { name: '' },
});
useMount(() => {
if (legalEntityId) {
fetchData();
}
});
const [legalEntityData, fetchData] = useAsyncFn(
() => LegalEntitiesService.getLegalEntity(legalEntityId),
[]
);
useEffect(() => {
if (
!legalEntityData.loading &&
legalEntityData.value &&
!legalEntityData.error
) {
const data: any = legalEntityData.value.data;
setLegalEntity({ ...data });
} else if (legalEntityData.error) {
// console.log(legalEntityData.error.message);
}
}, [legalEntityData]);
return (...);
};
export default LegalEnityInformation;
我无法理解为什么 {} 类型上不存在属性 legalEntityId
我要添加接口/构造函数吗?
让我们将legalEntityId定义为一个数字,也许会更好?
之类的接口道具{legalEntityId? = 数字}?
答案 0 :(得分:0)
您正在从 URL 字符串访问 legalEntityId
,因此实际上它始终是 string
而不是 number
。如果您想要 number
,则必须使用 parseInt
进行转换。
useParams
是一个泛型,它不知道可以在当前 URL 上找到哪些参数,因此您必须告诉它。
要获得 string | undefined
:
const { legalEntityId } = useParams<{ legalEntityId?: string }>();
要获得 number | undefined
:
const params = useParams<{ legalEntityId?: string }>();
const legalEntityId = params.legalEntityId ? parseInt(params.legalEntityId) : undefined;