gpt4 book ai didi

reactjs - 在 Typescript React 中使用 setInterval()

转载 作者:行者123 更新时间:2023-12-04 00:28:16 25 4
gpt4 key购买 nike

我正在尝试转换基于 React 的计时器 example typescript 。

这个类看起来有点像这样:

export class Container extends
Component<IProps, IState> {

private timerID: NodeJS.Timeout | undefined; // stops a warning in DidMount

constructor(props: IRevovlingContainerProps) {
super(props);
this.state = { date: new Date() } as any;
}

componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}

componentWillUnmount() {
clearInterval(this.timerID); // error here on this.timerID
}

// ...

componentWillUnmount() this.timerID有一个错误:

[ts] Argument of type 'Timeout | undefined' is not assignable to parameter of type 'number | undefined'. Type 'Timeout' is not assignable to type 'number'. [2345]



我查了 index.d.ts , 声明 clearInterval() :
declare function clearInterval(intervalId: NodeJS.Timeout): void;

所以看起来我正在将一个正确类型的参数传递给 clearInterval() ,但它需要一个数字。请问我应该传递什么?

编辑:如果我更改我的 timerID 声明,则会在 this.timerID 中出现错误在 componentDidMount() :
private timerID: number | undefined; 
Type 'Timeout' is not assignable to type 'number'.

最佳答案

NodeJS.Timeout用于在 node 中运行时使用环境。由于您想使用浏览器 API,您必须使用 number作为 timerID 的类型.

此外,内置函数不应从 node 解析它们的类型。类型定义,就你而言。如果您有 @types/node已安装,如果不需要请卸载。这可能与您需要使用的类型相冲突。

关于reactjs - 在 Typescript React 中使用 setInterval(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54471000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com