arrays - 数组中的 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 }}
/>
解决方案
这个问题给了我洞察力: Array my be correct type in this case
const [selected, setSelected] = React.useState<string[]>([]);
和复选框:
checked={selected.indexOf(value._links.self.href) !== -1}
推荐阅读
- algorithm - 递归关系的最坏情况和最佳情况运行时复杂度 T(n) = 2T(n/2) + T(n-1) + 常数
- c# - C# 图表将字符串值分配给 Y 轴
- vi - Ubuntu 不保存 vi 目录,得到错误 e502: is a directory
- jspdf - JsPdf 2.3.1 html 放置
- matplotlib - 使用 matplotlib 在 Python 中绘制曲面
- mongodb - 如何通过 swi prolog 连接到 MongoDB 服务器?
- terraform - 带有 VMware Workstation 的 Terraform
- excel - 有没有一种更快或更聪明的方法来为每个人做 2 个?
- api - API Place 详细信息不提供某些城市的邮政编码
- ios - 资产目录中字体资产的定义是什么?