类型时钟上不存在 ReactJS 属性 timerID

Sco*_*cle 1 typescript reactjs

我是 react js 的新手,目前我正在尝试遵循官方 reactjs 文档,运行一些示例。最近我尝试了这个例子:https : //reactjs.org/docs/state-and-lifecycle.html

但是当我把这段代码:

import React from 'react';
import ReactDOM from 'react-dom';

class Clock extends React.Component {

    state = {
        date: new Date()
    };

    constructor(props:any) {
        super(props);
        this.timerID = 0;
    }    
    componentDidMount() {
        this.timerID = setInterval(
            () => this.tick(),
            1000
        );
      }

      componentWillUnmount() {
        clearInterval(this.timerID);
      }

      tick() {
        this.setState({
          date: new Date()
        });
      }           
    render() {
      return (
        <div>
          <h1>Hello, world!</h1>
          <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
        </div>
      );
    }
  }

  ReactDOM.render(
    <Clock />,
    document.getElementById('root')
  );
Run Code Online (Sandbox Code Playgroud)

但是在 componentDidMount() 函数中,我收到此错误:

属性 timerID 在类型时钟上不存在

我不确定这里有什么问题,我试图在状态声明附近声明 timerID,但它会导致其他错误,所以我想知道我做错了什么。顺便说一句,这是离子框架项目,不确定这是否会导致错误。

这些是我在 package.json 中的依赖项

 "dependencies": {
    "@ionic/react": "^4.8.0-rc.0",
    "@ionic/react-router": "^4.8.0-rc.0",
    "@types/jest": "24.0.11",
    "@types/node": "11.11.3",
    "@types/react": "^16.9.1",
    "@types/react-dom": "^16.8.5",
    "@types/react-router": "^5.0.3",
    "@types/react-router-dom": "^4.3.1",
    "ionicons": "^4.6.2",
    "react": "^16.9.0",
    "react-dom": "^16.9.0",
    "react-router": "^5.0.1",
    "react-router-dom": "^5.0.1",
    "react-scripts": "3.1.0",
    "typescript": "3.5.3"
  },
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

谢谢

Asa*_*viv 5

这个错误来自打字稿而不是来自 React,添加timerID到类属性

您将需要使用window.setInterval而不是setInterval单独使用,因为它会将其键入为NodeJS.Timeout

class Clock extends React.Component {
    timerID: number;

    state = {
        date: new Date()
    };

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

    componentWillUnmount() {
        clearInterval(this.timerID);
    }

    tick() {
        this.setState({
            date: new Date()
        });
    }

    render() {
        return (
            <div>
                <h1>Hello, world!</h1>
                <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
            </div>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Scoracle因为“Node”和浏览器都有“setInterval”函数,它们返回不同的类型,因此您必须指定使用浏览器中的函数而不是“Node” (2认同)