我在 Typescript
中有此代码:
const [history, setHistory] = useState([Array(9).fill(null)]);
const newHistory = history.slice(0, currentStep + 1);
当我想使用像这样的扩展运算符设置新状态时:setHistory(...newHistory);
我有错误:A spread argument must either have a tuple type or be passed to a rest parameter.
有人可以帮助我,我如何正确输入?
最佳答案
使用时 useState
, 索引 1
在返回的元组中是 setHistory
.那应该只接受一个参数(新值)。原始帖子中的示例将历史扩展为潜在的 8 个参数。它需要作为一个数组传递,它可以像 setHistory(newHistory)
一样简单.
如果目的是总是修改以前的状态,我会打电话setHistory(previousHistory => previousHistory.slice(x, y))
.
还!对于 Typescript,你需要像这样为 useState 声明一个类型 useState<History[]>(Array(9).fill(null));
在不声明类型的情况下, typescript 将推断出一些在这种情况下可能不是您想要的东西。
请注意,您并不总是需要为 useState 声明类型。实际上,我鼓励尽可能使用类型推断。如果初始值为 null 或 undefined,您将无法在 Typescript 中使用类型推断。
关于reactjs - spread 参数必须具有元组类型或传递给 rest 参数 React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68768781/