kingguy kingguy - 5 months ago 164
jQuery Question

this.setState() is not a function when using react with jquery inside componentDidmount

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 work, any one can help me? 3ks! 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;

Answer

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
  });
})
Comments