React / Typescript:this.setState不是一个函数

时间:2019-03-04 11:35:37

标签: reactjs typescript setstate

我是第一次使用React +打字稿工作。

interface IState {
  stateval: number;
}
class Forgotpassword extends React.Component<any, IState> {
  constructor(props: any){
    super(props);
    this.state = { stateval: 1 };
  }
  public submit() {  
    this.setState({ stateval:2 });
  }
  public render() {
    const { stateval} = this.state;
    return (
      <div className="App">
        <Button onClick={this.submit}>Send OTP</Button>
      </div>
    );
  }
}

当我单击“提交”按钮时,它会抛出

Uncaught TypeError: this.setState is not a function

3 个答案:

答案 0 :(得分:1)

无需添加构造函数方法或使用bind。箭头功能可以满足您的需求。

import React, { Component } from 'react';

interface IState {
  stateval: number;
}

export default class Forgotpassword extends Component<any, IState> {
  state = {
    stateval: 2
  }

  public submit = () => this.setState({ stateval: 2 });

  public render() {
    return (
      <div className="App">
        <Button onClick={this.submit}>Send OTP</Button>
      </div>
    );
  }
}

答案 1 :(得分:1)

您需要以类似函数的方式绑定您的方法或变换

interface IState {
  stateval: number;
}
class Forgotpassword extends React.Component<any, IState> {
  constructor(props: any){
    super(props);
    this.state = { stateval: 1 };
  }
  const submit = () => {  
    this.setState({ stateval:2 });
  }
  const render = () => {
    const { stateval} = this.state;
    return (
      <div className="App">
        <Button onClick={this.submit}>Send OTP</Button>
      </div>
    );
  }
}

我希望它有用

答案 2 :(得分:0)

请将您的Submit函数绑定到此:

this.submit = this.submit.bind(this)