我很难弄清楚如何键入useState
函数,因为它返回一个元组。本质上,我必须提供null
作为email
的初始值,即假设我不能在此处使用空字符串。
然后我有setEmail
函数来更新此状态值,该状态值将电子邮件作为字符串输入。
理想情况下,我想输入我的useState
,因此希望电子邮件尽可能为字符串或null。目前,它仅作为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
对于null
中指定的useState()
而言不是有效的类型
[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;
}
答案 0 :(得分:9)
已经在几个地方解决了这个问题:
https://dev.to/busypeoples/notes-on-typescript-react-hooks-28j2
https://codewithstyle.info/Using-React-useState-hook-with-TypeScript/
TLDR:当您的初始状态为空时,将类型参数传递给setState
例如:
class TabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
let bool = Target.current == .targetOne
let targetBasedViewController: UIViewController = bool ? FirstViewController() : SecondViewController()
targetBasedViewController.tabBarItem.title = bool ? "First" : "Second"
targetBasedViewController.tabBarItem.image = UIImage(named: bool ? "First" : "Second")
}
}
答案 1 :(得分:6)
您能尝试一下并告诉我是否可行吗?
const { useState } = React;
function Example() {
const [state, setState] = useState<{email: null | string, password: null | string}>({ email: null, password: null });
function setEmail(email: string) {
setState(prevState => ({ ...prevState, email }))
}
return <p>{state.email}</p>
}
答案 2 :(得分:0)
您可以使用TS映射类型来提高可读性,并且首选使用undefined而不是null值
const { useState } = React;
function Example() {
const [state, setState] = useState<Partial<{email: string, password: string}>>();
function setEmail(email: string) {
setState(prevState => ({ ...prevState, email }))
}
return <p>{state.email | ""}</p>
}