【问题标题】:Cannot read property 'setState' of undefined in ReactJs [duplicate]无法读取 ReactJs 中未定义的属性“setState”[重复]
【发布时间】:2020-12-05 14:14:16
【问题描述】:

我正在更改 ReactJS 中的状态变量,然后在 Element 中返回它,但收到错误消息:

TypeError: 无法读取未定义的属性“setState”

我只是在练习这个,这是我第一次遇到这个问题。我会很感激你的帮助。

APP.JS:

import React from 'react'
import './App.css'



class App extends React.Component {

  state = {
    alpha: "",
  }

  handleChange(e) {
    this.setState({ alpha: e.target.value })

  }

  render(){
    return(<>
    <input type="text" placeholder="Enter here..." onChange={this.handleChange} ></input>
    <h1>{this.state.alpha}</h1>
    </>)
  }
}

export default App;

【问题讨论】:

  • 这能回答你的问题吗? this.setState is undefined
  • 使用构造函数并使用绑定... this.handleChange = this.handleChange.bind(this);

标签: javascript reactjs


【解决方案1】:

尝试在构造函数中初始化你的状态并像下面这样绑定函数

constructor(props) {
        super(props);

        this.state = {
            alpha: ""
        };

        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(e) {
        this.setState({
            alpha: e.target.value
        });
    }

【讨论】:

    【解决方案2】:

    要么使用箭头函数

    handleChange=(e)=> {
        this.setState({ alpha: e.target.value })
      }
    

    或者像这样在构造函数中绑定它

    constructor(props){
     super(props);
     this.state = {
       alpha: "",
     }
    this.handleChange = this.handleChange.bind(this);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-09-11
      • 2017-07-09
      • 2018-12-16
      • 1970-01-01
      • 2018-07-25
      • 2017-04-23
      • 1970-01-01
      • 2019-08-27
      相关资源
      最近更新 更多