在获得useState() react以使用我的实现时遇到了一些问题。
const [email, setEmail ] = useState<string>("");<IonItem>
<IonLabel position={"stacked"}>Email</IonLabel>
<IonInput type={"email"} value={email} onIonChange={(event) => setEmail(event.detail.value)}/> </IonItem>我一直在setEmail(event.detail.value)上得到以下错误
TS2345:类型为'string \ null \ undefined‘的参数不能分配给'SetStateAction’类型的参数。其他类型的“未定义”不能分配给键入“SetStateAction”。
我有点不明白为什么我还会犯这个错误?我在这里阅读了关于使用useState<string>("");实现的答案的前一篇文章:
发布于 2021-03-17 22:02:36
您已经将useState值的类型定义为字符串。但是,event.detail.value的类型可能是字符串,也可以是null或undefined。因为setEmail是一个只接受字符串的函数,所以您尝试分配一个可能null或undefined TS抱怨的值。
可以将useState的定义更改为包含undefined和null
const [email, setEmail] = useState<string | undefined | null>("");或者,您可以确保存储的值始终是字符串。如果不支持Nullish合并算子(??)或标准逻辑OR (X)来用空字符串替换undefined或null,则使用??。
onIonChange={(event) => setEmail(event.detail.value ?? '')}发布于 2021-03-17 22:09:16
关于如何解决这个问题,已经有了一个合适的答案。
为什么会发生这种情况?,因为onIonChange的内部函数已经声明(类型记录)可能的返回值是null、undefined或string。因此,您必须先将值转换为空字符串(例如,null为空字符串)或更改状态变量的可能类型。
https://stackoverflow.com/questions/66681826
复制相似问题