Reputation: 91
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>
Upvotes: 5
Views: 9653
Reputation: 86220
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" />;
}
});
Upvotes: 4
Reputation: 91
I realized render is executed a lot of times, so is not better place to my ajax invocation (-_-)'
This way works fine:
<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>
Thank you for reading!
Upvotes: 1