【问题标题】:How do I declare and reassign a variable in React Class Component to store a setTimeout reference?如何在 React 类组件中声明和重新分配变量以存储 setTimeout 引用?
【发布时间】:2020-02-26 09:23:06
【问题描述】:

习惯于 React 函数组件,我通常在函数内部声明 const。但是现在我必须在类组件中声明一个变量,并尝试了三种不同的方式:

  constructor(props: HWTrendChartProps) {
    super(props);
    testVarible = 'this is a test'; // 'testVarible' is not defined.eslint(no-undef)
  }
  constructor(props: HWTrendChartProps) {
    super(props);
    this.testVarible = 'this is a test'; // Property 'testVarible' does not exist on type 'classname'.ts(2339)
  }
private static timeoutRef: any; // works but have to re-assign using classname.timeoutRef = blahblah;

我正在尝试将setTimeout 引用存储在类组件中,以便我可以从componentWillUnmount 中获取clearTimeout。如果可以避免,我不想添加它。

【问题讨论】:

  • 在构造函数中使用状态 constructor(props: HWTrendChartProps) { super(props); this.state={ testVarible: '这是一个测试'; } } 然后通过键入 this.state.testVariable 访问它
  • 您尝试的第二种类型应该可以工作,在小提琴中也为我工作。我认为您调用 setTimeout 的方式存在一些问题。您可以发布您调用 setTimeout 的部分吗?

标签: reactjs typescript settimeout


【解决方案1】:

你需要将属性声明为类的一个字段:

class MyClass {
 private testVariable: string
 constructor(props: HWTrendChartProps) {
    super(props);
    this.testVarible = 'this is a test'; // Property 'testVarible' does not exist on type 'classname'.ts(2339)
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-27
    • 2011-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    相关资源
    最近更新 更多