在React中遇到回调函数问题

时间:2016-02-02 10:25:22

标签: javascript reactjs

我在我的一个React类中操作回调函数时遇到问题。我基本上是在点击时调用checkSource,如果符合特定要求,我想调用handleSubmitClick。我觉得这与我打电话this.handleSubmitClick有关,但我不明白。我的理解是this指的是我创建的组件对象。如果是这种情况,不应该只调用该函数并执行吗?

完整的组件在这里:

var React = require('react');

module.exports = React.createClass({
  getInitialState: function() {
    return {
      text: ''
    }
  },
  handleTextInput: function(event){
    this.setState({text: event.target.value})

  },
  checkSource: function(){
    var clientId = 'xxxx';
    var resolve = 'http://api.soundcloud.com/resolve?url=';
    $.get(resolve + this.state.text + '&client_id=' + clientId, function(data) {
      $.get('http://api.soundcloud.com/users/' + data.user.id + '/?client_id=' + clientId, function(data) {
        if(data.followers_count < 3000) {
          console.log("handleSubmitClick now");
          this.handleSubmitClick();
        } else {
          return false;
        }
      });
    });
  },
  handleSubmitClick: function() {
    console.log('handleSubmitClick going')
    console.log(this.state.text)
      var linkStore = this.props.linkStore
      linkStore.push(this.state.text)
      this.setState({text: ''})
      this.props.handleListSubmitClick(linkStore)
      console.log(this.props.linkStore)

  },
  render: function() {
    return <div className="row">
      <div className="col-md-8 col-md-offset-2">
        <div className="text-center">
          <h1>Soundcloud3k</h1>
        </div>
        <div className="input-group">
          <input
            onChange = {this.handleTextInput}
            type="text"
            className="form-control"
            placeholder="Search fr..."
            value={this.state.text} />
          <span className="input-group-btn">
            <button
              onClick={this.checkSource}
              className="btn btn-default"
              type="button">Submit!</button>
          </span>
        </div>
      </div>
    </div>
  }


});

这是checkSource调用

的渲染函数

checkSource功能的控制台日志按预期工作,但我无法让handleSubmitClick做任何事情。我在控制台中没有收到任何错误或任何错误。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

$.get回调this未引用您的组件时,您应为每次回调设置this。另外,ajax回调中的return false没有意义,所以你可以删除它

checkSource: function(){
  var clientId = 'xxxx';
  var resolve = 'http://api.soundcloud.com/resolve?url=';

  $.get(resolve + this.state.text + '&client_id=' + clientId, function(data) {
    $.get('http://api.soundcloud.com/users/' + data.user.id + '/?client_id=' + clientId, function(data) {
      if(data.followers_count < 3000) {
        this.handleSubmitClick();
      }
    }.bind(this));
  }.bind(this));
},