reactjs - 如果我想存储对象数组,如何定义 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.
解决方案
您收到此错误是因为{}
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;
推荐阅读
- javascript - 检查 react-native npm 包的最低 Android(Sdk) 版本
- ios - 尝试从 android studio 打开时,Xcode 中的 Flutter 打开模块会出错?
- c# - C# 更改先前分配的值
- python - sklearn模型预测在dask网格上
- python - 与 Bronkhorst 质量流量传感器通信 - 设备没有序列号?
- apache-spark - 使用 Apache Spark 3 从 Cosmos DB 流式传输数据
- kubernetes - Trino 舵图
- android - 当惰性列列表项较长时,键盘覆盖Jetpack Compose中的Textfield
- reactjs - 导出的变量“store”已经或正在使用来自外部模块错误 Redux toolkit 和 redux 的名称“$CombinedState”
- python - 想刮flipkart