Reactjs带渲染的意外无限循环

Rul*_*awa 5 javascript ajax reactjs

我使用React实现了Include组件.它从网址加载内容.这个测试工作,但也产生一个意外的无限循环与渲染......为什么?

<script type="text/jsx">
  /** @jsx React.DOM */
  var Include = React.createClass({
    getInitialState: function() {
      return {content: 'loading...'};
    },
    render: function() {
      var url = this.props.src;
      $.ajax({
        url: url,
        success: function(data) {
          this.setState({content: data});
        }.bind(this)
      });
      return <div>{this.state.content + new Date().getTime()}</div>;
    }
  });

  var Hello = React.createClass({
    render: function() {
        return <Include src="hello.txt" />;
    }
  });
  React.renderComponent(
    <Hello />,
    document.getElementById('hello')
  );
</script>
Run Code Online (Sandbox Code Playgroud)

Rul*_*awa 1

我意识到渲染被执行了很多次,所以这不是我的 ajax 调用更好的地方 (-_-)'

这种方式效果很好:

<script type="text/jsx">
  /** @jsx React.DOM */
  var Include = React.createClass({
    getInitialState: function() {
      var url = this.props.src;
      $.ajax({
        url: url,
        success: function(data) {
          this.setState({content: data});
        }.bind(this)
      });
      return {content: 'loading...'};
    },
    render: function() {
      return <div>{this.state.content + new Date().getTime()}</div>;
    }
  });

  var Hello = React.createClass({
    render: function() {
        return <Include src="hello.txt" />;
    }
  });
  React.renderComponent(
    <Hello />,
    document.getElementById('hello')
  );
</script>
Run Code Online (Sandbox Code Playgroud)

感谢您的阅读!

  • 很高兴看到您解决了问题!我建议的一个小建议是将 ajax 调用移至 componentWillMount 方法中。结果是相同的,但使用 componentWillMount 方法可以更好地分离关注点。我附上了一个小提琴,这样你就可以明白我的意思了。Ps - React 很棒这是 [jsfiddle](http://jsfiddle.net/NXCyC/50/) (2认同)