【问题标题】:How to setInterval in React with Typescript如何使用 Typescript 在 React 中设置时间间隔
【发布时间】:2018-08-01 23:49:18
【问题描述】:

我正在尝试在 react/typescript 中呈现动态进度条。我能够在反应中做到这一点,但将其转换为打字稿给了我;

[ts] 类型“Jockey”上不存在属性“setInterval”。 任何

setInterval 内部调用componentDidMount 时带有警告下划线。

仅使用 react 我在 componentDidMount 中使用了 this.interval = setInterval(this.timer, this.state.interval); 并且它有效,但是使用 typescript 的严格输入,我不知道该怎么做。

Jockey.tsx

import * as React from 'react';

interface Props {
    color: string;
    avatar: string;
}

interface State {
    interval: number;
    progress: number;
}

export class Jockey extends React.Component<Props, State> {

    constructor(props: Props) {
        super(props);
        this.state = {
          interval: Math.floor(Math.random() * 500),
          progress: 0,
        };
    }

    componentDidMount () {
        this.setInterval(this.timer, this.state.interval);
    }

    timer () {
        this.setState({ progress: this.state.progress + 1 });
        console.log('anyhting');
        
        (this.state.progress >= 99) ? this.setState({ progress: 100 }) : this.setState({ progress: 0 }) ;
    }

    render() {
        return (
            <div>
                <div className="App-lane">
                    {/* <img src={ this.props.avatar } alt=""/> */}
                    <progress value={this.state.progress} color={this.props.color} max="100" />
                </div>
            </div>
        );
    }
}

【问题讨论】:

  • this.setInterval中删除this
  • setInterval 是全局 window 对象的方法,不是任何自定义类
  • 谢谢!工作...
  • 看起来我在 timer() 中没有正确使用 this.setState。我似乎在设置 progress 时遇到问题。

标签: javascript reactjs typescript


【解决方案1】:

this.setInterval() 不存在。

我假设您正在尝试创建一个 interval 并保存一个 reference 以便您以后可以 clear 它。

请参阅下面的粗略示例,了解如何实现这一目标。

设置间隔

componentDidMount () {
  this.interval = setInterval(this.timer, this.state.interval)
}

清除间隔

componentWillUnmount() {
  clearInterval(this.interval)
}

进一步阅读

有关详细信息,请参阅 React Docs: State and Lifecycle 中的 setInterval() 参考资料。

一切顺利✌️

【讨论】:

  • 如果我使用this.interval = setInterval(this.timer, this.state.interval),这将不起作用。如果我像上面的 cmets 那样带走 this 就可以了。看起来我在timer() 中也没有正确使用this.setState。我似乎在设置progress 时遇到问题。记住我正在使用打字稿
  • timer() 似乎不是 boundthis。您可以使用Arrow Function 重新声明或调用它。否则请参阅this article
猜你喜欢
  • 2017-12-03
  • 2011-11-09
  • 2014-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
  • 2021-10-05
  • 2010-09-20
相关资源
最近更新 更多