gpt4 book ai didi

javascript - 带有渲染的 Reactjs 意外无限循环

转载 作者:搜寻专家 更新时间:2023-11-01 04:08:56 25 4
gpt4 key购买 nike

我使用 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>

最佳答案

这是一个更可靠的包含组件。差异,

  • 渲染应该是纯的(那里不能做ajax)
  • getInitialState 应该是纯的
  • 如果 Prop 是动态的,例如<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" />;
}
});

关于javascript - 带有渲染的 Reactjs 意外无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24842505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com