【发布时间】:2022-07-05 22:36:55
【问题描述】:
如图所示,我想为我的网页警报声明一个反应状态挂钩。起初,我希望没有显示警报。并且每当用户单击某个按钮时,我想显示一个带有消息的成功警报(如果出现问题,则会出现错误警报)。我将调用 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)
那么,谁能告诉我如何告诉 useState 对象参数,我将在未来分配它。或者我应该尝试以其他方式隐藏网站警报?这是代码..
const [alert, setAlert] = useState(null);
const showAlert = (message, type) => {
setAlert({
msg: message,
type: type,
});
setTimeout(() => {
setAlert(null);
}, 2000);
【问题讨论】:
-
请将代码图片替换为基于文本的minimal reproducible example
-
定义状态类型
useState(null as any) -
useState<{msg: string, type: string}>(null)。如果您在 tsconfig 中有严格的 null 检查,您将无法设置 null。您可以从 tsconfig 中删除它,也可以useState<{msg: string, type: string} | null>(null) -
@Rashomon 我试过了。我得到这两个错误。 1. 解析错误:Unexpected token, expected "," (10:41)eslint {squigly error on null word} 2. 类型断言表达式只能在TypeScript files.ts(8016) {error line under any word}
-
@Dilshan 我为您的解决方案收到了这些错误。 1. 类型 'number' 必须有一个返回 iterator.ts(2488) 的 '[Symbol.iterator]()' 方法 2. (property) msg: any Operator ' (initialState: S | (() => S)): [S, Dispatch
>]; (): [S |未定义,调度>]; }' 和 '{ 味精:任何;类型:任何; }'.ts(2365) '|'布尔类型不允许使用运算符。考虑使用“||”相反.ts(2447) 3. 与自身进行比较可能毫无意义。eslintno-self-compare Object 可能为 'null'.ts(2531)
标签: javascript reactjs typescript react-hooks use-state