如图所示,我想声明一个 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);
这个解决方案不适合我。
最佳答案
您需要稍微不同地声明您的 useState
const [alert, setAlert] = useState<{ msg: any; type: any } | null>(null);
另一种选择是使用 undefined
const [alert, setAlert] = useState<{ msg: any; type: any } | undefined>();
希望对您有所帮助。
https://stackoverflow.com/questions/72870629/