首页 文章

使用setState()调用AJAX后状态不更新

提问于
浏览
1

在componentDidMount中进行AJAX调用后,我没有获得状态更新 . 我的api调用正在返回正确的数据 .

如果我在错误的生命周期组件中执行setState,是否有任何想法?在componentDidMount中发出AJAX请求,并在那里设置新状态 . 在构造函数中,我将状态设置为空数组

class DeliveryDateInput extends React.Component {
constructor(props) {
    super(props);
    this.getDeliveryDate = this.getDeliveryDate.bind(this);

    this.state = {
        selectDate: selectedDate || validDelDateArray[0],
        validDeliveryDateArray: validDelDateArray,
        firstDeliveryDay: [],
        lastDeliveryDay: [],
        selectedDate: [],
        deliveryDatesAllowed: [],
        offDays: [],
    };
}

componentDidMount () {
    console.log('App componentDidMount');
    this.getDeliveryDate();
}

componentWillUpdate(nextProps, nextState) {
    this.getDeliveryDate();
    console.log('Your prev offday state: ' + this.state.offday);
    console.log('Your next offday state: ' + nextState.offday);
}

getDeliveryDate() {
    const self = this;
    $.ajax({
        type: 'GET',
        url:  //deliveryDateAPI,
        contentType: 'application/json; charset=utf-8',
        success(data) {
            self.setState({
                firstDeliveryDay: data.firstDeliveryDate,
                lastDeliveryDay: data.lastDeliveryDay,
                selectedDate: data.firstDeliveryDate,
                deliveryDatesAllowed: data.deliveryDates,
                offDays: data.offDays,
            });
        },
        failure(errMsg) {
            console.log(errMsg);
        },
    });
}

1 回答

  • 3

    在React中,您必须将ajax回调函数绑定到组件(这是 .bind(this)

    你知道这个并且在你的构造函数中做了类似的事情,但是对于jquery ajax,它看起来会有点像:(并且这里不需要 self 变量)

    getDeliveryDate() {
        $.ajax({
            type: 'GET',
            url:  //deliveryDateAPI,
            contentType: 'application/json; charset=utf-8',
            success: function(data) {
                this.setState({
                    firstDeliveryDay: data.firstDeliveryDate,
                    lastDeliveryDay: data.lastDeliveryDay,
                    selectedDate: data.firstDeliveryDate,
                    deliveryDatesAllowed: data.deliveryDates,
                    offDays: data.offDays,
                });
            }.bind(this),
            error: function(errMsg) {
                console.log(errMsg);
            }.bind(this),
        });
    }
    

    我测试了上面的代码,它的工作原理 . 您可能不需要绑定 error 回调,因为如果您想在那里进行进一步操作,您仍然需要't do anything yet to the component, but maybe it'!

    如果这还不行,请在此处评论控制台上的错误,谢谢!

    ADDED MODIFICATION:

    请删除componentWillUpdate中的ajax调用,这将创建一个“永远”循环:

    componentWillUpdate(nextProps, nextState) {
        //this.getDeliveryDate();
        console.log('Your prev offday state: ' + this.state.offday);
        console.log('Your next offday state: ' + nextState.offday);
    }
    

    原因是:实际上,在设置状态之后,将执行 componentWillUpdate() ,如果再次运行ajax调用,此后它将再次设置为state,那么循环将永远持续!

相关问题