简体   繁体   中英

React/Typescript : this.setState is not a function

I am work in react + typescript for first time.

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>
    );
  }
}

When i click the submit button it throws

Uncaught TypeError: this.setState is not a function

There's no need to add the constructor method or use bind. An arrow function is fine for your needs.

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>
    );
  }
}

you need to bind your method or trasform in functional like

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>
    );
  }
}

i hope it useful

Please bind your submit function to this :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM