最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Polling not working in React JS mixin - Stack Overflow

programmeradmin2浏览0评论

So I created the following 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
            });
        });
    }
}

Note the console.log('hello'); in the poll function. I should see this every 15 seconds according to this logic.

Now lets look at a react ponent:

//= require ../../mixins/mon/polling.js
//= require ../../mixins/mon/state_handler.js
//= require ../../ponents/recent_signups/user_list.js

var RecentSignups = React.createClass({

    mixins: [Polling, StateHandler],

    getInitialState: function() {
        return {
            users: null,
            error_message: '',
            error: false
        }
    },

    ponentDidMount: function() {
        this.startPolling();
    },

    ponentWillUnmount: 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
    );
}

Here we see in the ponetDidMount function I am calling this.startPolling When the page loads, what I see after 1 second is:

hello
hello
  • A) its (poll fucntion) some how being called twice oO.
  • B) its (poll function) never being called again.

The reason I separated polling out is so that I can use it in other ponents on the same page and not duplicate code.

Very simply question(s):

Why and how do I fix this? I need it to poll ever 15 seconds and I should only see hello once when poll is called the first time.

So I created the following 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
            });
        });
    }
}

Note the console.log('hello'); in the poll function. I should see this every 15 seconds according to this logic.

Now lets look at a react ponent:

//= require ../../mixins/mon/polling.js
//= require ../../mixins/mon/state_handler.js
//= require ../../ponents/recent_signups/user_list.js

var RecentSignups = React.createClass({

    mixins: [Polling, StateHandler],

    getInitialState: function() {
        return {
            users: null,
            error_message: '',
            error: false
        }
    },

    ponentDidMount: function() {
        this.startPolling();
    },

    ponentWillUnmount: 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
    );
}

Here we see in the ponetDidMount function I am calling this.startPolling When the page loads, what I see after 1 second is:

hello
hello
  • A) its (poll fucntion) some how being called twice oO.
  • B) its (poll function) never being called again.

The reason I separated polling out is so that I can use it in other ponents on the same page and not duplicate code.

Very simply question(s):

Why and how do I fix this? I need it to poll ever 15 seconds and I should only see hello once when poll is called the first time.

Share Improve this question edited Sep 22, 2017 at 16:45 Trenton 12k11 gold badges59 silver badges64 bronze badges asked Sep 29, 2015 at 18:06 TheWebsTheWebs 12.9k32 gold badges115 silver badges220 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

On this line you call self.poll() and the result would be the timer:

self._timer = setInterval(self.poll(), 15000);

Instead pass the function:

self._timer = setInterval(self.poll, 15000);

As another option, in the spirit of "you're code's not working? just use someone else's instead!", react-async-poll is a handy ponent wrapper that you can use for polling.

发布评论

评论列表(0)

  1. 暂无评论