typescript spread参数必须具有元组类型或传递给rest参数React

dnph8jn4  于 2022-11-18  发布在  TypeScript
关注(0)|答案(5)|浏览(1505)

我在Typescript中有以下代码:
第一个
当我想使用spread运算符设置新的State时,如下所示:

setHistory(...newHistory);

我有错误:
spread参数必须具有Tuple类型或传递给rest参数。
有人能帮我吗,我怎么才能正确地打这个?

xghobddn

xghobddn1#

通常,可以使用apply来避免此类错误

setHistory(...newHistory); //drops error

setHistory.apply(null, newHistory) //works

但在您示例中存在一个问题:使用[[null, null, null...]]初始化历史记录,然后获取它,切片到[[null, null, ...], ...]并尝试将其设置回setHistory([null, null], null)
看起来您只需要使用setHistory(newHistory);

rn0zuynd

rn0zuynd2#

简单地说:
因为直接使用spread运算符,所以向useState函数传递了多个参数,但useState函数只接受一个参数。相反,使用spread运算符创建一个数组,并传递该数组。

const newObject = [...newHistory];
setHistory(newObject);

// or, even simpler: 
setHistory([...newHistory]);

// NOT the below - this is passing in multiple arguments.
setHistory(...newHistory);
o2rvlv0m

o2rvlv0m3#

这对我来说非常有效!

setHistory(...(newHistory as []));
dgjrabp2

dgjrabp24#

当使用useState时,返回的元组中的索引1setHistory。它应该只接受一个参数(新值)。原始帖子中的示例将历史分布到可能的8个参数中。它需要作为一个数组传递,可以像setHistory(newHistory)一样简单。
如果目的是总是修改先前的状态,我将调用setHistory(previousHistory => previousHistory.slice(x, y))
另外!对于Typescript,你需要为useState声明一个类型,比如useState<History[]>(Array(9).fill(null));。如果不声明一个类型,typescript将推断出一些东西,在这种情况下,可能不是你想要的。
请注意,您并不总是需要为useState声明一个类型。实际上,我鼓励您尽可能使用类型推断。如果初始值为null或未定义,您将无法在Typescript中使用类型推断。

zzoitvuj

zzoitvuj5#

可以通过将值赋给变量来解决。

const latestHistory = {...newHistory}

setHistory(latestHistory);

相关问题