heron2014 / weather-redux-app

Weather app build in React and Redux
0 stars 0 forks source link

Errors #3

Open heron2014 opened 8 years ago

heron2014 commented 8 years ago

Error-binding-context:

error-binding

This error is result of not binding the event function to the instance of our class (SearchBar)


export default class SearchBar extends Component {
  constructor(props) {
    super(props);

    this.state = { term: '' };
  }

  onInputChange(event) { 
    this.setState({ term: event.target.value }) //setState is not bind to anything
  }

  render() {
    return (
      <form className="input-group">
        <input
          placeholder="Get a five day forecast in your favourite cities"
          className="form-control"
          value={this.state.term}
          onChange={this.onInputChange} />
      </form>
    );
  }
}

Fix:


export default class SearchBar extends Component {
  constructor(props) {
    super(props);

    this.state = { term: '' };
    this.onInputChange = this.onInputChange.bind(this);
  }

  onInputChange(event) { 
    this.setState({ term: event.target.value })
  }

  render() {
    return (
      <form className="input-group">
        <input
        ...
          onChange={this.onInputChange} />
      </form>
    );
  }
}

this.onInputChange = this.onInputChange.bind(this) - > second this refer to instance of SearchBar which has existing function called onInputChange, now bind this function to this which is SearchBar and replace onInputChange with the new bound instance of this function.