[英]React shouldComponentUpdate too much recursion
我正在使用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
。
進行搜索后發現此答案建議使用componentWillReceiveProps
設置狀態,但是當我使用它時,圖像不會在第一個自動刷新上更新,而僅在第二個自動刷新上更新。
這是我實現componentWillReceiveProps
之后的當前流程:
...等等。 您能幫我理解為什么會這樣嗎?
注意:我需要使用狀態,因為需要對componentDidMount進行檢查以確認圖像有效
過去, 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;
}
通過添加比較舊道具和狀態及其替換的條件,它應停止遞歸。
注意:我無法測試此代碼,所以也許關閉
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.