【发布时间】:2023-03-07 14:29:01
【问题描述】:
我无法弄清楚如何键入 useState 函数,因为它返回一个元组。本质上,我必须提供null 作为email 的初始值,即假设我不能在这里使用空字符串。
然后我有setEmail 函数来更新这个状态值,它将电子邮件作为字符串接收。
理想情况下,我想输入我的useState,因此如果可能,它希望电子邮件为字符串或空值。目前它只继承它null
import * as React from "react";
const { useState } = React;
function Example() {
const [state, setState] = useState({ email: null, password: null });
function setEmail(email: string) {
setState(prevState => ({ ...prevState, email }))
}
return <p>{state.email}</p>
}
setEmail 函数返回以下错误,因为函数参数中的 string 不是 useState() 中指定的 null 的有效类型
[ts]
Argument of type '(prevState: { email: null; password: null; }) => { email: string; password: null; }' is not assignable to parameter of type 'SetStateAction<{ email: null; password: null; }>'.
Type '(prevState: { email: null; password: null; }) => { email: string; password: null; }' is not assignable to type '(prevState: { email: null; password: null; }) => { email: null; password: null; }'.
Type '{ email: string; password: null; }' is not assignable to type '{ email: null; password: null; }'.
Types of property 'email' are incompatible.
Type 'string' is not assignable to type 'null'. [2345]
(parameter) prevState: {
email: null;
password: null;
}
【问题讨论】:
-
当你用空字符串改变null时会发生什么?我的意思是如果你使用
useState({email: "", password: ""})? -
@lomse 可以解决这个问题,但正如我在问题中提到的那样,我想找出一种使用
someType | null方法的方法,即如果我将来使用自定义接口但想要初始值为空或未定义
标签: reactjs typescript react-hooks