【问题标题】:How to fix error argument of type undefined is not assignable to parameter of type 'string or () => string usng typescript and react?如何修复 undefined 类型的错误参数不可分配给'string or () => string usng typescript 类型的参数并做出反应?
【发布时间】:2020-08-21 18:00:06
【问题描述】:

我收到错误,未定义类型的错误参数不可分配给'字符串或()=>字符串类型的参数使用打字稿并做出反应。

下面是我的代码,

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 || '')/>
    );
 }

我不确定是什么导致了这个错误。有人可以帮我解决这个问题。谢谢。

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    您将状态成员的初始值设置为undefined,它不是字符串。因此,要修复它,您必须:

    1. 用字符串初始化状态成员,而不是undefined

       const [itemId, setItemId] = React.useState<string>(
           "" // <=== or whatever string makes sense as the initial value
       );
      

    2. 将状态成员的类型更改为string | undefined(一个union type),这允许成员为字符串undefined

       const [itemId, setItemId] = React.useState<string | undefined>(
           undefined // −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^
       );
      

    旁注:如果您要初始化为 undefined,则可以完全不使用该参数:= useState&lt;string|undefined&gt;()

    【讨论】:

      【解决方案2】:

      由于你用undefined初始化状态,所以状态的类型不是string而是string | undefined(这是一个联合类型,意味着值可以是stringundefined

      export const useSomething =()=> {
          const [itemId, setItemId] = React.useState<string | undefined>(
              undefined //getting error here
          );
          const toggle = (itemId: string) => {
              setItemId(itemId);
              return {toggle, itemId};
      
          }
       }
      

      这可能会导致其他地方出现错误(您期望字符串,但不是 undefined 也是一种选择,但您应该修复这些以处理 undefined

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-27
        • 1970-01-01
        • 2021-12-30
        • 1970-01-01
        • 2021-05-25
        • 2022-12-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多