我使用React来实现Include组件。它从url加载内容。这个测试工作,但也产生了一个意想不到的无限循环渲染…为什么?
<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>
这是一个更可靠的Include组件。差异,
- 渲染应该是纯的(不能在那里做ajax)
- getInitialState应该是纯的
- 如果道具是动态的,例如
<Include url={this.state.x} />
,它应该更新
var 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" />;
}
});
我意识到渲染是执行了很多次,所以不是更好的地方,我的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>
感谢您的阅读!