如何将usestate()初始值声明为null,然后稍后给它一个对象值?
如图所示,我想向我的网页提示。起初,我希望没有显示警报。每当用户单击某些按钮时,我都想显示带有消息的成功警报(如果出现问题,错误警报)。我将调用ShowAlert函数以消息和键入功能参数来执行此操作。这就是为什么可能有多种警报的原因。因此,我创建了此警报对象,并附有具有初始值“ null”的挂钩。但是编辑给了我这个错误。
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)
因此,有人可以告诉我如何告诉我们将来我会分配它的对象参数。还是我应该尝试以其他方式隐藏网站警报?这是代码..
const [alert, setAlert] = useState(null);
const showAlert = (message, type) => {
setAlert({
msg: message,
type: type,
});
setTimeout(() => {
setAlert(null);
}, 2000);
此解决方案对我不起作用。
As can be seen in the image, I want to declare a react state hook to the alert of my webpage. At first, I want that there is no alert shown. And whenever user is clicking some button, I want to show a success alert with a message (error alert if something goes wrong). I will call showAlert function to do this with message and type as function parameter. That's why there can be more than one type of alert. So, I created this alert object and attached hook with initial value "NULL". But the editor gives me this error.
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)
So, can someone tell me how I can tell useState the object parameters that I will allot it in future. Or should I try to hide the website alert in some other way? Here is the code..
const [alert, setAlert] = useState(null);
const showAlert = (message, type) => {
setAlert({
msg: message,
type: type,
});
setTimeout(() => {
setAlert(null);
}, 2000);
This solution is not working for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从您提到的错误的外观看来,您似乎正在使用Typescript。
实现预期结果的一种方法是使用。
此外,您可以通过添加 enum>类型。
From the looks of the error you mentioned, it seems you're using TypeScript.
One way to achieve the desired outcome is to use generics.
Furthermore, you can improve readability by adding an enum and a type.
您可以在下方进行USESTATE类型
You can do it below way for useState type
您需要声明您的USESTATE的
另一种选择是使用
未定义的
希望对您有所帮助。
You need to declare your useState a little differently
Another alternative is the use
undefined
Hope that helps.
有2种解决方案:
There are 2 solutions: