【问题标题】:How do I fix setState typescript argument errors?如何修复 setState 打字稿参数错误?
【发布时间】:2021-03-16 00:26:25
【问题描述】:

我只是想知道如何解决这个问题,以及在哪里学习如何正确格式化这些东西。感谢您提供任何指导,无论如何,当我尝试传入用于我的 useState 的 useState 对象时,我在打字稿中遇到错误。

The error I'm getting is this

当我使用useState时,我应该如何声明箭头函数变量的类型?这个很复杂,它会引发一堆错误。这是为了动态提供附加到我们的电话输入道具的道具的电话类型选项。代码工作正常,我只想将它传递给 useState 而不会出现这个 dang 错误,并学习如何正确地将东西传递给 useState

以下是处理此部分的代码:

  const [availablePhoneTypes, setAvailablePhoneTypes] = useState<PhoneTypes[]>(ALL_PHONE_TYPES);
  const [currentPhoneTypes, setCurrentPhoneTypes] = useState<[{index: number, type: string}]>([]);
  const handlePhoneTypeChange = (
    e: any,
    index: number
  ) => {
    const selectedPhoneType = e.target.value;
    // const tmp = availablePhoneTypes.filter(type => type != selectedPhoneType);
    // setAvailablePhoneTypes(tmp);
    /////////////////////////////////////////////
    /////////////////////////////////////////////
  
    // Manage/Update the selected phone types
    if (currentPhoneTypes.filter((data: {index: number;}) => data.index === index).length != 0) {
      const updateCurrentPhoneTypes = currentPhoneTypes.map((data: {index: number, type: string;}) => {
        if (data.index == index) data.type = e;
        return data;
      });
      setCurrentPhoneTypes(updateCurrentPhoneTypes);
    } else {
      // .push may throw an error on the useState currentPhoneTypes
      // const currentPhoneTypesInsert = 
      setCurrentPhoneTypes(currentPhoneTypes.push({index: index, type: selectedPhoneType}));
      console.log(`index: ${index}, type: ${selectedPhoneType}, new current phone types`, currentPhoneTypes);
    }
  
    // Set the available phone types 
    const theSelectedPhoneTypes = currentPhoneTypes.map(data: {type: string;} => data.type);
    const unselectedPhoneTypes = ALL_PHONE_TYPES.filter(type => !theSelectedPhoneTypes.includes(type));
    console.log('Here are the selected phone types: ', theSelectedPhoneTypes);
    console.log('the available phone types: ', unselectedPhoneTypes);
  
    setAvailablePhoneTypes(unselectedPhoneTypes);
  };

如果你们对代码感到好奇,我会在这里,今晚我休息一下,看看你们的想法后会再工作一个小时。我很感激,任何事情都会有所帮助!

【问题讨论】:

    标签: reactjs typescript use-state


    【解决方案1】:

    第 2 行是错误的。 [{index: number, type: string}] 声明一个具有固定数量元素的数组字面量(即 tuple)。应该是{index: number, type: string}[](或Array&lt;{index: number, type: string}&gt;

    
      const [currentPhoneTypes, setCurrentPhoneTypes] = useState<{index: number, type: string}[]>([]);
    

    【讨论】:

    • 这应该是一个数组。一次最多可以声明 4 个电话号码,每个电话号码都有一个类型。我想使用 usestate 变量来跟踪每个电话号码(按索引)以及每个电话号码的关联类型,因为每种类型都必须是唯一的。等等,这就是我声明对象数组的方式吗?
    • @roninMo 我刚刚给你看了。再读一遍。 {index: number, type: string}[](或Array&lt;{index: number, type: string}&gt; 都声明了一个对象数组。:)
    猜你喜欢
    • 2019-05-13
    • 2020-09-20
    • 1970-01-01
    • 2022-11-10
    • 2022-01-26
    • 2022-06-29
    • 1970-01-01
    • 2018-12-17
    • 2020-06-09
    相关资源
    最近更新 更多