如何解决“无法读取未定义的属性”错误的反应?

时间:2019-05-21 20:52:40

标签: javascript reactjs

嗨,我想返回在第一次投票完成后解决的诺言...

我有一个start_polling方法,我想对其进行修改,以便它返回一个promise,当items_promise得到解决时,它会得到解决...我不确定该怎么做。

我尝试了什么?

我在start_polling方法中创建了一个诺言,当在item_promise的方法中执行item_promise_finish()时,该诺言将得到解决。

一旦解决了start_polling中的这个诺言,我就会调用handle_location方法。

它工作正常,但有时我遇到错误,无法读取未定义的属性。

我该如何解决。

下面是代码

componentDidUpdate(prevProps, prevState) {
    const {state, props} = this;
    const current_id = props.item && props.item.id;
    const prev_id = prevProps.item && prevProps.item.id;
    if (current_id !== prev_id) {
        this.stop_polling();
        this.setState(this.get_initial_state(), () => {
            this.start_polling();
        });
     } else {
         const prev_poll = this.should_poll(prevProps, prevState);
         const next_poll = this.should_poll(props, state);
         if (prev_poll !== next_poll) {
             if (next_poll) {
                 this.start_polling();
             } else {
                this.stop_polling();
         }
    }
    if (this.props.location.search) {
        this.start_polling().then(() => {
            this.handle_location();
        })
}

start_polling = () => {
    if (this.should_poll(this.props, this.state)) {
        this.poll();
        return new Promise((resolve) => { 
            this.item_promise_finish=resolve; 
        });
    }
};

poll = () => {
    let still_polling = true;
    if (this.cancel_poll_request) {
        this.cancel_poll_request();
    }
});

const items_promise = client.get_items(this.props.item.id,  
cancel_poll_promise);
items_promise.then((request) => {
    const next_items = [];
    let something_changed = false;
    for (const new_item of request.response) {
        const old_item = this.state.items.find(
            old_item =>
                old_item.id === new_item.id);
        if (old_item) {
            next_items.push(old_item);
        } else {
            something_changed = true;
            next_items.push(new_item);
        }
    }

    if (something_changed) {
        const next_state = {items: next_items};
        this.setState(next_state);
    }
}).then(() => {
    if (still_polling) {
        this.poll_timeout = setTimeout(this.poll, 100s);
    }
    this.item_promise_finish();
}).catch(this.props.notifications.request_error);
};

有人可以让我知道我要去哪里哪里或要解决此问题的方法。谢谢。

0 个答案:

没有答案