当在componentDidmount中使用与jquery进行反应时,this.setState()不是一个函数 [英] this.setState() is not a function when using react with jquery inside componentDidmount

查看:274
本文介绍了当在componentDidmount中使用与jquery进行反应时,this.setState()不是一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用es6和jquery的ajax函数做出反应时,我得到 this.setState()不是一个函数错误。我尝试使用 this.componentDidmount = this.componentDidmount.bind(this); 在构造函数中绑定,但仍然不起作用。

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!

这是我的代码:

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;


推荐答案

this componentDidMount()中的回调函数的c $ c>上下文未设置。

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

这篇关于当在componentDidmount中使用与jquery进行反应时,this.setState()不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆