This.setState () is not a function when using a reaction with jquery inside componentDidmount

When I use reaction with es6 function and jquery ajax, I got an error this.setState() is not a function. I tried to link this inside the constructor using this.componentDidmount = this.componentDidmount.bind(this);, but still not working.

Can someone help me? Thank you

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} last gist is
        <a href={this.state.lastGistUrl}>here</a>.
      </div>
    )
  }
}

export default UserGist;
0
source share
1 answer

The context thisfor the callback function inside is componentDidMount()not set.

You can use the arrow function to do this, for example:

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

Source: https://habr.com/ru/post/1651061/


All Articles