typescript 使用 React 的 useState 钩子时键入可空状态的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53338922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct way to type nullable state when using React's useState hook
提问by Ilja
I am having trouble figuring out how to type useState
function since it returns a tuple. In essence, I have to provide null
as initial value for email
i.e. lets assume I can't use empty string here.
我无法弄清楚如何键入useState
函数,因为它返回一个元组。本质上,我必须null
为email
ie提供初始值,假设我不能在这里使用空字符串。
I then have setEmail
function to update this state value, which takes in email as string.
然后我有setEmail
更新这个状态值的功能,它将电子邮件作为字符串。
ideally I would like to type my useState
so it expects email to be either string or null if possible. At the moment it inherits it as only null
理想情况下,我想输入 my,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>
}
Following error is returned for setEmail
function since string
in function argument is not valid type for null
specified in useState()
为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;
}
回答by Nurbol Alpysbayev
Can you try this and tell me if it works?
你能试试这个并告诉我它是否有效吗?
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>
}
回答by Adrien Gardou
you can use TS mapped types to improve readability and prefer undefined over null values
您可以使用 TS 映射类型来提高可读性,并且更喜欢 undefined 而非空值
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>
}
回答by Sean O'Leary
This is addressed in a few spots already:
这已经在几个地方得到解决:
https://dev.to/busypeoples/notes-on-typescript-react-hooks-28j2
https://dev.to/busypeoples/notes-on-typescript-react-hooks-28j2
https://codewithstyle.info/Using-React-useState-hook-with-TypeScript/
https://codewithstyle.info/Using-React-useState-hook-with-TypeScript/
TLDR: pass a type argument to setState when you have an empty initial state
TLDR:当初始状态为空时,将类型参数传递给 setState
eg:
例如:
const [email, setEmail] = useState<string>();