I using React to implemented Include component. It load content from url. This test works but also produces an unexpected infinite loop with render... why?
<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>
                To get rid of your infinite loop, simply use an empty dependency array like so: const [count, setCount] = useState(0); //only update the value of 'count' when component is first mounted useEffect(() => { setCount((count) => count + 1); }, []); This will tell React to run useEffect on the first render.
If you update the state directly inside your render method or a body of a functional component, it will cause an infinite loop.
You could solve the error by passing an initial value or a function to the useState() hook to initialize the state. Copied! We passed a function to the useState method. The function will only get invoked the first time the component renders and will calculate the initial state.
To break a map() loop in React: Call the slice() method on the array to get a portion of the array. Call the map() method on the portion of the array.
This is a more reliable Include component. The differences,
<Include url={this.state.x} />, it should updatevar Include = React.createClass({
  getInitialState: function() {
    return {content: 'loading...'};
  },
  componentDidMount: function(){ 
    this.updateAJAX(this.props.url); 
  },
  componentWillReceiveProps: function(nextProps){
    // see if it actually changed
    if (nextProps.url !== this.props.url) {
      // show loading again
      this.setState(this.getInitialState);
      this.updateAJAX(nextProps.url);
    }
  },
  updateAJAX: function(url){
    $.ajax({
      url: url,
      success: function(data) {
        this.setState({content: data});
      }.bind(this)
    });
  },
  render: function() {
    return <div>{this.state.content}</div>;
  }
});
var Hello = React.createClass({
  render: function() {
    return <Include src="hello.txt" />;
  }
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With