[英]How to fix error argument of type undefined is not assignable to parameter of type 'string or () => string usng typescript and react?
i am getting error error argument of type undefined is not assignable to parameter of type 'string or () => string usng typescript and react.我收到未定义类型的错误错误参数不可分配给'字符串或()=>字符串类型的参数使用 typescript 并做出反应。
below is my code,下面是我的代码,
export const useSomething =()=> {
const [itemId, setItemId] = React.useState<string>(
undefined //getting error here
);
const toggle = (itemId: string) => {
setItemId(itemId);
return {toggle, itemId};
}
}
function Parent() {
const {itemId, toggle} = useSomething();
return (
<Child anotherId={anotherId} itemId={itemId} toggle={toggle}/>
);
}
function Child({itemId, anotherId, toggle) {
return (
<Button onClick={() => toggle(anotherId || '')/>
);
}
i am not sure what is causing this error.could someone help me with this.我不确定是什么导致了这个错误。有人可以帮我解决这个问题。 thanks.
谢谢。
You're setting the initial value of the state member to undefined
, which isn't a string.您将 state 成员的初始值设置为
undefined
,这不是字符串。 So to fix it, you have to either:因此,要修复它,您必须:
Initialize the state member with a string, instead of undefined
;用字符串而不是
undefined
初始化 state 成员;
const [itemId, setItemId] = React.useState<string>( "" // <=== or whatever string makes sense as the initial value );
or或者
Change the type of the state member to string | undefined
将 state 成员的类型更改为
string | undefined
string | undefined
(a union type ), which allows the member to be a string or be undefined
: string | undefined
( 联合类型),它允许成员是字符串或undefined
:
const [itemId, setItemId] = React.useState<string | undefined>( undefined // −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^ );
Side note: If you're initializing to undefined
, you can just leave the argument off entirely: = useState<string|undefined>()
.旁注:如果您要初始化为
undefined
,则可以完全关闭该参数: = useState<string|undefined>()
。
Since you initialize the state with undefined
, the type of the state is not string
but rather string | undefined
由于您使用
undefined
初始化 state ,因此 state 的类型不是string
而是string | undefined
string | undefined
(this is a union type, meaning the value can either be string
or undefined
) string | undefined
(这是一个联合类型,这意味着该值可以是string
或undefined
)
export const useSomething =()=> {
const [itemId, setItemId] = React.useState<string | undefined>(
undefined //getting error here
);
const toggle = (itemId: string) => {
setItemId(itemId);
return {toggle, itemId};
}
}
This may lead to errors in other places (where you expect a string, but not undefined
is also an option but you should fix those to handle undefined
这可能会在其他地方导致错误(您期望一个字符串,但不是
undefined
也是一种选择,但您应该修复那些以处理undefined
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.