首页 > 解决方案 > 如果我想存储对象数组,如何定义 useState 挂钩所期望的类型?

问题描述

我正在尝试使用useState钩子存储一组对象,但无法获得描述它所期望类型的语法。我要存储的类型是Array<Updates>.

这是我的代码:

const [messages, setMessages] = useState<any>([]);

更新

我选择通过数组进行映射,Updates现在想存储每个Update是普通对象的对象,但Argument of type '{}' is not assignable to parameter of type 'Update | (() => Update)'.使用此代码时出现错误:

const [messages, setMessages] = useState<Update>({}); // object in brackets is underlined with the error.

标签: reactjstypescriptreact-hooks

解决方案


您收到此错误是因为{}is not Update。如果我理解正确,您希望 Update 可以为空。

像这样的东西应该适合你:

const [messages, setMessages] = useState<Update | null>(null);

这意味着messages(顺便说一句,您可能应该将其重命名update为更好的可读性)可以是 null 或Update对象类型。

如果您尝试在没有空检查的情况下使用它,这将产生错误。

类似的东西messages.name会导致消息可能为空的错误。

您可以通过编写类似的东西const name = messages && messages.name或简单的 if 语句来修复它。

if (messsages)
 // do something here
 const name = messages.name;
}

如果您在尝试访问它时 100% 的消息永远不会为空,则可以使用以下方法打开它!const name = messasges!.name;


推荐阅读