![](/img/trans.png)
[英]How to rerender a React component once mounted without calling setState in componentDidMount
[英]How to render a component without calling setState or making componentWillUpdate to be executed in React?
因此,假设我有2个React组件,如下所示:
var Parent = React.createClass({
getInitialState: function(){
return ({
child: <Children state="someState" />
});
},
parentFunction: function() {
this.setState({
child: <Children state="otherState" />
});
},
render: function() {
return (
<div>
{this.state.child}
</div>
);
}
//...other methods
});
var Children = React.createClass({
componentWillMount: function() {
this.getData();
},
componentWillUpdate: function() {
this.getData();
}
getData: function() {
var that = this;
$.getJSON("https://some.url", function(result){
//Do something with result
that.setState();
});
}
//other methods ....
});
首次渲染Parent时,Children也是首次渲染。 因此,将执行Children的componentWillMount,然后依次调用Children的getData。 由于getData调用作为异步函数的getJSON,因此它无法“按时”返回第一次渲染的Child的结果。 因此,我的解决方案是在getJSON完成后调用setState(),结果将再次使Children呈现。 到目前为止一切都还好。
但是,当我调用parentFunction来更新Children时,就会出现问题。 由于Children已更新,将执行其componentWillUpdate,因此将调用getData()。 但是,在完成结果之后,getData()依次调用setState()。 setState()使componentWillUpdate被执行。 这就是我陷入无限循环的方式。
我正在寻找一种无需调用setState或不执行componentWillUpdate即可呈现组件的方法。 但是我还没有找到。 我不确定如何解决此问题。 任何帮助,将不胜感激。
无需寻找无需调用setState即可呈现的方法。
为了避免循环,只需使用componentWillReceiveProps()代替componentWillUpdate即可,如React文档中所述 。
但是,您甚至可以使用以下模式来测试组件是否应该真正更新 :
var Children = React.createClass({
componentWillMount: function() {
this.getData();
},
componentWillReceiveProps: function(nextProps) {
// some sort of logic that defines if new
// props are different than the previous ones
if(nextProps.data !== this.props.data)
{
this.getData();
}
}
getData: function() {
var that = this;
$.getJSON("https://some.url", function(result){
//Do something with result
that.setState();
});
}
}
据我说,您还以错误的方式使用了父母的状态。
状态应包含有关组件本身(而不是其他组件)的数据和属性。
像这样重写它会很有帮助:
var Parent = React.createClass({
getInitialState: function(){
return ({
something: [] // example
});
},
parentFunction: function() {
this.setState({
something: [12] // example
});
},
render: function() {
return (
<div>
<Children state={this.state.something} />
</div>
);
}
//...other methods
});
希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.