【发布时间】:2017-05-12 00:22:58
【问题描述】:
在 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);
},
});
}
【问题讨论】:
-
componentDidMount里面获取数据和设置状态没有问题。获取数据后是否调用success回调?并且没有名为failure的$.ajax选项。您需要将其更改为error。 -
你解决了这个问题了吗,如果是,请考虑投票或接受我的回答,谢谢^^!