简体   繁体   English

用打字稿反应 useState

[英]React useState with typescript

I have this code我有这个代码

interface AccountData {
    country:  number |null ;
}
const [accountData, setAccountData] = useState<AccountData>({ country:null });

Until we assign a value to a country it can be an undefined, null, or empty string.在我们为国家赋值之前,它可以是未定义的、空的或空的字符串。

Then I set the country value like this然后我像这样设置国家/地区值

 const handleChange = (e: number) => {
        if (!isNaN(e)) {
            setAccountData({ country: e });
           
        }
    };

And then I try to pass the value of the country to a function that requires the parameter as a number, I got this error然后我尝试将国家/地区的值传递给需要参数作为数字的函数,我收到此错误

<Button
 small
 onClick={() => {
 handleSubmit(accountData.country);
}}>save</Button>

Type 'null' is not assignable to type 'number'.类型 'null' 不能分配给类型 'number'。

Which make sense typescript assumes this can be null sometimes.这有道理打字稿假设这有时可以为null So I check if this is a number before I pass to the function like this所以我在传递给这样的函数之前检查这是否是一个数字

onClick={() => {
if (!isNaN(accountData.country)) {
handleSubmit(accountData.country);
}
}}

But the error is still there.但是错误仍然存​​在。 How can I fix this?我怎样才能解决这个问题?

Without seeing your handleSubmit function, I'm guessing it's annotated with number .没有看到您的handleSubmit函数,我猜它是用number注释的。 There is a chance country can be null when this is submitted.提交时,国家有可能为null Therefore TypeScript isn't happy with this.因此 TypeScript 对此并不满意。

Something like this might help:像这样的事情可能会有所帮助:

const handleSubmit = (input: number | null) => {
  // stuff
}

You can use as keyword to specify type number for country .您可以使用as关键字为country指定类型number

<Button
 small
 onClick={() => {
 handleSubmit(accountData.country as number);
}}>save</Button>

Refer: Type Narrowing参考: 类型缩小

If Counrt your value undefined , null , or empty string so can define also any .如果Counrt您的值undefinednullempty字符串,则也可以定义any Which can accept undefined , null , or empty .可以接受undefinednullempty

Learn more about typescript了解有关打字稿的更多信息

interface AccountData {
    country: number | null | any;
}

const [accountData, setAccountData] = useState<AccountData>({ country:null });

const handleSubmit = (input: number | null | any) => {
   // do some stuff here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM