所以我創建了以下的mixin:輪詢在不工作作出反應JS混入
var Polling = {
startPolling: function() {
var self = this;
setTimeout(function() {
self.poll();
if (!self.isMounted()) {
return;
}
self._timer = setInterval(self.poll(), 15000);
}, 1000);
},
poll: function() {
if (!this.isMounted()) {
return;
}
var self = this;
console.log('hello');
$.get(this.props.source, function(result) {
if (self.isMounted()) {
self.setState({
error: false,
error_message: '',
users: result
});
}
}).fail(function(response) {
self.setState({
error: true,
error_message: response.statusText
});
});
}
}
注意console.log('hello');
在poll
功能。根據這個邏輯,我應該每15秒看一次。
現在讓我們來看一個反應成分:
//= require ../../mixins/common/polling.js
//= require ../../mixins/common/state_handler.js
//= require ../../components/recent_signups/user_list.js
var RecentSignups = React.createClass({
mixins: [Polling, StateHandler],
getInitialState: function() {
return {
users: null,
error_message: '',
error: false
}
},
componentDidMount: function() {
this.startPolling();
},
componentWillUnmount: function() {
if (this._timer) {
clearInterval(this._timer);
this._timer = null;
}
},
shouldComponentUpdate: function(nextProps, nextState) {
if (this.state.users !== nextState.users ||
this.state.error !== nextState.error ||
this.state.error_message !== nextState.error_message) {
return true;
}
return false;
},
renderContents: function() {
if (this.state.users === null) {
return;
}
return (
<div>
<ul>
<UserList users={this.state.users} />
</ul>
</div>
);
},
render: function() {
return (
<div>
{this.loading()}
{this.errorMessage()}
{this.renderContents()}
</div>
)
}
});
RecentSignupsElement = document.getElementById("recent-signups");
if (RecentSignupsElement !== null) {
ReactDOM.render(
<RecentSignups source={ "http://" + location.hostname + "/api/v1/recent-signups/" } />,
RecentSignupsElement
);
}
在這裏,我們在componetDidMount
功能我打電話this.startPolling
看到頁面加載時,我在1秒之後看到的是:
hello
hello
- A)其(
poll
fucntion)一些如何被稱爲兩次oO。 - B)其(
poll
函數)永遠不會再被調用。
我分開查詢的原因是我可以在同一頁面上的其他組件中使用它,而不是重複的代碼。
非常簡單的問題:
爲什麼以及如何解決這個問題?我需要它輪詢15秒,當poll
第一次被調用時,我只應該看到hello
。