简体   繁体   中英

ReactJS cant read property 'setState' of undefined

Using this as a reference, react.js - show a message on and after form submission , I am trying to replicate something similar, but I am encountering an error in console, "Uncaught TypeError: Cannot read property 'setState' of undefined". I am unable to pinpoint where I losing the reference of 'this' in my state component.

import React from 'react'
import RadarInput from './radarInput'

class RadarForm extends React.Component {
  constructor(props) {
    super(props);
  }
  onFormSubmit = (data, cb) => {
    cb(data);
  }
  render() {
    return (
      <div>
        <RadarInput OnRadarSubmit={this.onFormSubmit.bind(this)} />
      </div>
    )
  }
}

export default RadarForm



import React from 'react'

class RadarInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value:"Hello!", message: ''}
  }
  handleChange = (evt) => {
    this.setState({value: evt.target.value });
  }
  sendContent = function(e) {
    console.log("I'm in content")
    console.log("this is e: ", this.state.value);
    e.preventDefault();
    var radarNum = this.state.value
    this.setState({value: '', message: 'Please wait ...'});
    this.props.OnRadarSubmit({
      value: radarNum
    }, function(data){
      console.log("data in cb ", data.value);
      this.setState({ message: data.value });
    });
  }
  render() {
    return (
      <div>
        Title: <div>{this.state.message}</div>
        <form onSubmit={this.sendContent.bind(this)}>
          Radar Number: <input type="text" value={this.state.value} onChange={this.handleChange.bind(this)} />
          <input type="submit" value="Submit" />
        </form>
      </div>
    )
  }
}

export default RadarInput

You need to set this to a variable outside of your OnRadarSubmit() callback first.

var self = this;

this.props.OnRadarSubmit({ value: radarNum}, function(data){
    console.log("data in cb ", data.value);
    self.setState({ message: data.value });
});

The reason being that in the callback, this does not refer to the class scope any longer, so by setting self , you are explicitly using the enclosing scope.

Further reading .

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