[英]React shouldComponentUpdate too much recursion
I'm building a dashboard with auto-update every few seconds using React. 我正在使用React构建每隔几秒钟自动更新的仪表板。 I'm getting the properties from an Ajax call and passing them to the components, which until now has been working fine.
我正在从Ajax调用中获取属性,并将它们传递给组件,直到现在为止,它们一直运行良好。
In one of the components, I need to set the image source that gets updated every x seconds automatically but in this case I need to use state. 在其中一个组件中,我需要设置每x秒自动更新一次的图像源,但是在这种情况下,我需要使用状态。
This is my component: 这是我的组件:
var ImageContainer = React.createClass({
getInitialState: function(){
return { src: this.props.initialImage};
},
shouldComponentUpdate: function(nextProps, nextState){
this.setState({ src: this.props.initialImage });
return true;
},
render: function() {
return (
<div className="col-md-8 col-sm-12 nopadding post-image vcenter" >
<img src={this.state.src} className="img-responsive center-cropped"/>
</div>
);
}
});
This works good but gives too much recursion error
. 这很好用,但是给出
too much recursion error
。
Did a search and found this answer advising to use componentWillReceiveProps
to set the state, but when I use it, the image is not updated on the first auto-fresh, only on the second. 进行搜索后发现此答案建议使用
componentWillReceiveProps
设置状态,但是当我使用它时,图像不会在第一个自动刷新上更新,而仅在第二个自动刷新上更新。
Here's the current flow after I implement componentWillReceiveProps
: 这是我实现
componentWillReceiveProps
之后的当前流程:
...and so on. ...等等。 Can you help me understand why this happens?
您能帮我理解为什么会这样吗?
Note: I need to use state because there's the need to run a check on componentDidMount to confirm the image is valid 注意:我需要使用状态,因为需要对componentDidMount进行检查以确认图像有效
I have had similar issues with componentWillReceiveProps
in the past. 过去,
componentWillReceiveProps
有类似的问题。 It is assumed that if it is called it has new props and it seems it isn't always the case. 假设它被称为具有新的道具,而且似乎并非总是如此。
See: https://facebook.github.io/react/blog/2016/01/08/A-implies-B-does-not-imply-B-implies-A.html 参见: https : //facebook.github.io/react/blog/2016/01/08/A-implies-B-does-not-imply-B-implies-A.html
The recursion will probably be due to setting state in shouldComponentUpdate
without returning false to stop the render. 递归可能是由于应在
shouldComponentUpdate
设置状态而没有返回false来停止渲染。 It may be worth trying something along the lines of: 可能值得尝试以下方法:
shouldComponentUpdate: function(nextProps, nextState) {
this.setState({ src: nextProps.initialImage });
return nextProps.initialImage !== this.props.initialImage;
}
By adding a condition that compares the old props and state to their replacements, it should stop recursion. 通过添加比较旧道具和状态及其替换的条件,它应停止递归。
NOTE: I haven't been able to test this code, so maybe off 注意:我无法测试此代码,所以也许关闭
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.