我正在构建一个仪表板,每隔几秒钟使用React自动更新一次。我从Ajax调用中获取属性,并将它们传递给组件,直到现在,组件一直运行良好。
在其中一个组件中,我需要设置每x秒自动更新一次的图像源,但在这种情况下,我需要使用状态。
这是我的组成部分:
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>
);
}
});这很好,但给了too much recursion error。
进行了搜索,发现this answer建议使用componentWillReceiveProps设置状态,但是当我使用它时,图像不会在第一个自动更新,而只是在第二个更新。
下面是实现componentWillReceiveProps后的当前流
...and等。你能帮我理解为什么会发生这种事吗?
注意:我需要使用state,因为需要对componentDidMount进行检查以确认图像是有效的
发布于 2016-02-17 16:58:47
在过去,我和componentWillReceiveProps也有过类似的问题。人们认为,如果它被称为,它有新的道具,似乎并不总是如此。
请参阅:https://facebook.github.io/react/blog/2016/01/08/A-implies-B-does-not-imply-B-implies-A.html
递归可能是由于在shouldComponentUpdate中设置状态而不返回false来停止呈现。也许值得尝试一些类似于以下内容的东西:
shouldComponentUpdate: function(nextProps, nextState) {
this.setState({ src: nextProps.initialImage });
return nextProps.initialImage !== this.props.initialImage;
}通过添加一个将旧道具和状态与其替换进行比较的条件,它应该停止递归。
注意:我还没能测试这段代码,所以也许可以关闭
https://stackoverflow.com/questions/35461510
复制相似问题