如何修复 setState 打字稿参数错误?

时间:2021-03-16 00:26:25

标签: reactjs typescript use-state

我只想知道如何解决这个问题,以及在哪里学习如何正确格式化这些东西。感谢您提供任何指导,无论如何,当我尝试传入我用于 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);
  };

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

1 个答案:

答案 0 :(得分:1)

第 2 行是错误的。 [{index: number, type: string}] 声明具有固定数量元素的数组文字(即 tuple)。它应该是 {index: number, type: string}[](或 Array<{index: number, type: string}>


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