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;