this.IsMounted()不是函数

时间:2015-07-22 23:06:28

标签: ajax reactjs

我正在尝试构建一个简单的React App。它从ajax调用中检索数据并将其呈现给页面。问题是我在ajax调用之后设置了this.props的状态。我收到此错误:

Uncaught TypeError: this.isMounted is not a function

我一直在浏览教程并查看一些示例代码,例如此页面通过反应网站https://facebook.github.io/react/tips/initial-ajax.html上的ajax加载信息,但我不知道会导致这个问题错误。这是我的代码:

var ANiceReminderApp = React.createClass({
  getInitialState: function(){
    return {
      quotes: []
    };
  },
  componentDidMount: function(){
    $.ajax({
      headers: { 'X-Mashape-Key':'xxxxxx'},
      url: 'https://healthruwords.p.mashape.com/v1/quotes/',
      type: 'GET',
      dataType: 'JSON',
      success: function(data){
        var quote = data[0].media;
        if(this.isMounted()){
          this.setState({
            quotes: quote
          });
        }
      }
    });
  },

  render: function() {
    return (
      <div className="container">
        hello world
        <img src={this.state.quotes}/>
        <button>Need more inspiration?</button>
      </div>

    );
   }
 });
 React.render(<ANiceReminderApp />, document.body); 

提前致谢!

2 个答案:

答案 0 :(得分:4)

在事件处理程序中,require指的是引发事件的对象。在您的情况下,那将是this对象,它实际上缺少jqXHR方法。

要处理这种情况,您需要保留对外部.isMounted()的引用并在事件处理程序中使用该引用,或使用this强制该函数保留外部上下文。 / p>

以下是如何执行后一种方法的示例:

function.bind()

答案 1 :(得分:2)

@ gilly3的答案解释了这个问题。但是,我更喜欢不同的解决方案:React将有效地自动绑定类方法,这意味着this将正确引用该实例。所以我通常使用方法作为回调:

React.createClass({

  componentDidMount: function(){
    $.ajax({
      // the method is already bound to the component
      success: this.onDataReceived
    });
  },

  onDataReceived: function(data) {
    var quote = data[0].media;
    if(this.isMounted()){
      this.setState({
        quotes: quote
      });
    }
  },

  // ...

});

这有几个好处:

  • 至少在理论上,React的绑定比使用.bind更有效。如果您必须多次拨打.bind多次通话,情况尤其如此。

  • 它使回调更容易测试。

  • 通过其他代码路径调用回调逻辑更容易(例如,如果您还想接受通过props提供的数据)。

它也值得看this discussion,这表明将来可能会弃用isMounted - 在这种情况下建议的路径是保存对AJAX请求的引用并中止它在componentWillUnmount