【问题标题】:Property doesnt exist on type类型上不存在属性
【发布时间】:2021-07-10 14:05:54
【问题描述】:
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 定义为一个数字,也许会更好?

类似接口 Props { legalEntityId? =数字}?

【问题讨论】:

  • React Router 文档说“useParams 返回一个由 URL 参数的键/值对组成的对象”。我的想法是检查该对象的内容(可能是 console.log),看看是否存在 legalEntityId 属性。

标签: javascript reactjs typescript types react-router


【解决方案1】:

您正在从 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;

【讨论】:

    猜你喜欢
    • 2021-01-09
    • 2017-07-22
    • 2023-03-26
    • 2023-04-02
    • 2019-12-20
    • 2021-12-07
    • 2016-03-14
    • 2017-02-25
    相关资源
    最近更新 更多