在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);
},
});
}
答案 0 :(得分: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
回调,因为你还没有对组件做任何事情,但如果你想在那里做进一步的操作,它仍然是必要的!
如果这还不行,请在此处评论您的控制台上的错误,谢谢!
添加修改
请删除componentWillUpdate中的ajax调用,这将创建一个" forever"循环:
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,那么循环将永远持续!