this.setState() is not a function when using react

2019-09-12 10:38发布

问题:

This question already has an answer here:

  • How to access the correct `this` inside a callback? 10 answers

When I use react with es6 and jquery's ajax function, I got this.setState() is not a function error. I tried bind this within constructor using this.componentDidmount = this.componentDidmount.bind(this);, but still not working.

Can any one help me? Thanks!

Here is my code:

import React from 'react';
import $ from 'jquery';

class UserGist extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userName: '',
      lastGistUrl: ''
    };
  }

  componentDidMount() {
    this.serverRequest = $.get(this.props.source, function(result) {
      let lastGist = result[0];
      this.setState({
        userName: lastGist.owner.login,
        lastGistUrl: lastGist.html_url
      });
    });
  }

  componentWillUnmount() {
    this.serverRequest.abort();
  }

  render() {
    return(
      <div>
        {this.state.userName}'s last gist is
        <a href={this.state.lastGistUrl}>here</a>.
      </div>
    )
  }
}

export default UserGist;

回答1:

The this context for the callback function inside componentDidMount() isn't set.

You could use an arrow function to do it, like so:

this.serverRequest = $.get(this.props.source, (result) => {
  let lastGist = result[0];
  this.setState({
    userName: lastGist.owner.login,
    lastGistUrl: lastGist.html_url
  });
})