【问题标题】:React Hooks and TypeScript Fetching API: Object is possibly 'null'React Hooks 和 TypeScript Fetching API:对象可能为“空”
【发布时间】:2019-10-22 21:44:52
【问题描述】:

我正在做一个关于 React Hooks 和获取数据的教程。这是我获取客户并将其映射到列表中的组件:

const useFetch = (url: string) => {
  const [customers, setCustomers] = useState<null | []>(null);
  const [loading, setLoading] = useState(true);

  // Similiar to componentDidMount() and componentDidUpdate()
  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(url);
      setCustomers(result.data);
      setLoading(false);
    };
    fetchData();
  });

  return { customers, loading };
};

const url = 'https://jsonplaceholder.typicode.com/users';

export const LatestCustomers: React.FC<Props> = ({
  description
}: Props): JSX.Element => {
  const { customers, loading } = useFetch(url);

  return (
    <Container>
      {loading ? (
        <div>...Loading...</div>
      ) : (
        <tr>
          {customers.map(customer => (
            <div key="user.id">{customer.name}</div>
          ))}
        </tr>
      )}
    </Container>
  );
};

这样,我得到了错误:

Object is possibly 'null'.  TS2531

    108 |               ) : (
    109 |                 <tr>
  > 110 |                   {customers.map(customer => (
        |                    ^
    111 |                     <div key="user.id">{customer.name}</div>
    112 |                   ))}
    113 |                 </tr>

我该如何解决这个问题?

【问题讨论】:

  • 也许const { customers = [], loading } = useFetch(url);会解决
  • 这个问题有几种解决方案,但基本上都是:1.确保它永远不会为空;或 2. 处理它可能为 null 的可能性(null.mapTypeError)。

标签: reactjs typescript api react-hooks


【解决方案1】:

处理可空值的可靠解决方案是在 fp-ts 和 fromNullable 中使用选项

https://github.com/gcanti/fp-ts/blob/master/src/Option.ts

例子:

{fromNullable(customers).map(x=&gt; {...})}

有趣的文章: https://davetayls.me/blog/2018/05/20/fp-ts-01-working-with-nullable-values

其他更直接的方法:

{customers &amp;&amp; customers.map(x =&gt; ( ...

【讨论】:

  • 但是它给了Property 'name' does not exist on type 'never'.
  • 请发布您正在尝试的代码,我很乐意提供帮助!谢谢
【解决方案2】:

因为提供给useState 的类型是null | [],所以customers 被赋予了该类型签名。

有几种方法可以解决这个问题。我的建议是从一个空数组开始:

const [customers, setCustomers] = useState<[]>([]);

或者,如果您希望保持可选类型,那么您应该首先检查customers 不是null

{customers && customers.map(customer => ( ...

或者,如果您确定它总是被定义,您可以使用 TypeScript non-null assertion ! 运算符:

{customers!.map(customer => (

【讨论】:

  • 我都试过了,它给了Property 'name' does not exist on type 'never'.
  • 所以你的问题已经解决了,但是现在 TS 期望输入客户。您是否为客户对象定义了类型?如果是这样,请使用它:const [customers, setCustomers] = useState&lt;Customer[]&gt;([]);
猜你喜欢
  • 1970-01-01
  • 2019-11-10
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 2022-01-14
  • 1970-01-01
  • 2021-12-01
相关资源
最近更新 更多