gpt4 book ai didi

javascript - 如何声明 useState() 初始值为 null,然后再给它一个对象值?

转载 作者:行者123 更新时间:2023-12-05 09:27:07 25 4
gpt4 key购买 nike

enter image description here

如图所示,我想声明一个 react 状态 Hook 到我的网页警报。起初,我希望没有显示警报。每当用户单击某个按钮时,我想显示一 strip 有消息的成功警报(如果出现问题,则发出错误警报)。我将调用 showAlert 函数来使用消息和类型作为函数参数来执行此操作。这就是为什么可以有不止一种类型的警报。因此,我创建了这个警报对象并附加了初始值为“NULL”的钩子(Hook)。但是编辑给我这个错误。

Argument of type '{ msg: any; type: any; }' is not assignable to parameter of type 'SetStateAction<null>'. Object literal may only specify known properties, and 'msg' does not exist in type '(prevState: null) => null'.ts(2345)

那么,有人能告诉我如何告诉 useState 我将来分配给它的对象参数吗?或者我应该尝试以其他方式隐藏网站警报吗?这是代码..

const [alert, setAlert] = useState(null);

const showAlert = (message, type) => {
setAlert({
msg: message,
type: type,
});

setTimeout(() => {
setAlert(null);
}, 2000);

enter image description here

这个解决方案不适合我。

最佳答案

您需要稍微不同地声明您的 useState

const [alert, setAlert] = useState<{ msg: any; type: any } | null>(null);

另一种选择是使用 undefined

const [alert, setAlert] = useState<{ msg: any; type: any } | undefined>();

希望对您有所帮助。

关于javascript - 如何声明 useState() 初始值为 null,然后再给它一个对象值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72870629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com