背景: 我试图用反应更新基于一些Web服务的JSON响应一些UI元素,但因为我有很多的元素如果元素的HashCode被更新,我试图通过只拉json来减少带宽。在我的应用程序的上下文中,我无法更新我的ajax调用的异步行为。只有在异步调用完成后,强制更新元素的正确方法是什么?
我意识到WillUpdate中的设置状态是错误的。阵营:异步调用之前最后的渲染方法被调用更新状态
例子:
getInitialState: function getInitialState() {
return { hash: 0, json: {}};
},
//Only get the step asJSON if the hash is updated
shouldComponentUpdate: function(nextProps, nextState) {
return this.state.json.hash != nextState.json.hash;
},
tick: function(){
this.updateHash();
},
updateHash: function updateHash(){
something.getUpdateHash(function(data){
var hashR = data.responseJSON;
this.setState({hash: hashR});
}.bind(this));
},
updateJSON: function(){
//This is an asynchronous call
something.getJSON(function(data){
var stepJ = jQuery.parseJSON(data.responseJSON);
this.setState({json: stepJ});
}.bind(this));
},
componentWillMount: function(){
this.updateJSON();
},
componentDidMount: function(){
this.interval = setInterval(this.tick, 10000);
},
componentWillUpdate: function(nextState, nextProps){
//Way to update json state w/o affecting state?
},
render: function render() {
/** Only do render after updateJSON is complete **/
}
我没有想到这个!谢谢+1 – Chrizt0f