首页 > 解决方案 > 数组中的 Typescript IndexOf 问题使用状态

问题描述

在我的列表组件中,我需要为每个元素保留一个字符串数组,它们表示选中的数组(通过复选框)以执行删除等操作,并且我想传递链接“themes/:id”并不总是索引,它们是来自 MySQL 的 ID,这就是为什么从 MUI 页面获取索引号数组的更简单算法对我来说还不够。但是在 indexOf(element) 行打字稿说“'string'类型的参数不能分配给'never'类型的参数。” 为什么 indexOf 需要 never 类型?我能做些什么来解决这个问题?

const [selected, setSelected] = React.useState<Array<string>| [] >([]);

 const selectHandler = (listId: string) => () => {
   const currentIndex = selected.indexOf(listId);
   const newSelected = [...selected];
   if (currentIndex === -1) {
      newSelected.push(element);
   } else {
      newSelected.splice(currentIndex, 1);
   }
    setSelected(newSelected);
 }

复选框组件更进一步,还有一个错误“任何不能分配给从不”。“value._links.self.href”来自返回这种 JSON 的 spring data rest。

<Checkbox
  edge='end'
  onChange={selectHandler(value._links.self.href)}
  checked={checked.indexOf(value._links.self.href) !== -1}
  inputProps={{ 'aria-labelledby': labelId }}
/>

标签: arraysreactjstypescriptreact-hooksindexof

解决方案


打字稿中的“不可分配给永不类型的参数”错误是什么?

这个问题给了我洞察力: Array my be correct type in this case

const [selected, setSelected] = React.useState<string[]>([]); 

和复选框:

checked={selected.indexOf(value._links.self.href) !== -1}

推荐阅读