我有以下代码:
var Panel = React.createClass({
getInitialState: function () {
return {
user_id: null,
blogs: null,
error: false,
error_code: '',
error_code: ''
};
},
shouldComponentUpdate: function(nextProps, nextState) {
if (nextState.error !== this.state.error ||
nextState.blogs !== this.state.blogs ||
nextState.error_code !== this.state.error_code
) {
return true;
}
},
componentDidMount: function() {
var self = this;
var pollingInterval = setInterval(function() {
$.get(self.props.source, function(result) {
if (self.isMounted()) {
self.setState({
error: false,
error_code: '',
error_message: '',
blogs: result.user.blogs,
user_id: result.user.id
});
}
}.bind(self)).fail(function(response) {
self.setState({
error: true,
error_code: response.status,
error_message: response.statusText
});
}.bind(self));
}, 1000);
},
render: function() { ... }
});
要关注的重要部分是componentDidMount
无论是否存在错误,都会每秒获取一次。假设出现错误,渲染函数将显示适当的方法。因此,对于所有强烈和目的,此代码完全按照我希望它执行的操作,它获取,如果失败,它会再次获取直到成功。
但我需要做一些改变,这就是我迷失的地方。我想说:取一次,通过或失败 - 没关系。然后在初始提取后每15秒再次尝试 - 无论通过还是失败
我通常会使用一个主干集合和路由器以及一个轮询助手来完成所有这些操作,但在这种特定情况下,不需要额外的开销。所以那就是我难倒的地方。 如何实现我想要实现的目标?
答案 0 :(得分:12)
你应该能够稍微重构你的代码,以便能够以几种不同的方式调用你的轮询函数(例如手动,然后以指定的间隔):
componentDidMount: function() {
this.startPolling();
},
componentWillUnmount: function() {
if (this._timer) {
clearInterval(this._timer);
this._timer = null;
}
},
startPolling: function() {
var self = this;
setTimeout(function() {
if (!self.isMounted()) { return; } // abandon
self.poll(); // do it once and then start it up ...
self._timer = setInterval(self.poll.bind(self), 15000);
}, 1000);
},
poll: function() {
var self = this;
$.get(self.props.source, function(result) {
if (self.isMounted()) {
self.setState({
error: false,
error_code: '',
error_message: '',
blogs: result.user.blogs,
user_id: result.user.id
});
}
}).fail(function(response) {
self.setState({
error: true,
error_code: response.status,
error_message: response.statusText
});
});
}