そこで、次の mixin を作成しました。
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 秒ごとに表示されるはずです。
次に、react コンポーネントを見てみましょう。
//= 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
関数) いくつかの方法で oO が 2 回呼び出されます。 - B)その (
poll
function) が再び呼び出されることはありません。
ポーリング アウトを分離した理由は、同じページの他のコンポーネントで使用でき、コードが重複しないようにするためです。
非常に簡単な質問:
これを修正する理由と方法を教えてください。15 秒ごとにポーリングする必要があり、初めて呼び出されたhello
ときに 1 回だけ表示する必要があります。poll