我有一个表单根据日期范围显示数据。在第一次加载时,>它显示最近1小时的数据。我正在使用反应日期> > > >选择器渲染开始和结束时间。当用户更改开始和结束时> > >日期,以下函数被调用。在这个函数中,我试图设置> > >具有用户选择的开始和结束日期的状态,但状态始终保持> > >上一个开始和结束日期值
refreshTableOnDateChange(startDateSelected,endDateSelected) {
this.setState({startDate: null, endDate: null});
console.log("inside refreshTableOnDateChange this.state.startDate is", startDateSelected);
console.log("inside refreshTableOnDateChange this.state.endDate is", endDateSelected);
let startDateFormatted = startDateSelected.format('YYYY-MM-DD HH:mm');
let endDateFormatted = endDateSelected.format('YYYY-MM-DD HH:mm');
this.setState({startDate: startDateFormatted, endDate: endDateFormatted});
this.forceUpdate();
console.log("start date is", this.state.startDate);
console.log("end date is", this.state.endDate);
this.load(this.state.orderType);
}
答案 0 :(得分:0)
setState没有立即改变状态 - 来自Reacts文档:
https://facebook.github.io/react/docs/react-component.html#setstate
setState()不会立即改变this.state但会创建一个 待定状态转换。调用后访问this.state 方法可以返回现有值。没有 保证调用setState和调用的同步操作 为获得业绩增长而受到批评。
此代码应该呈现给您以便您查看更新。:
console.log("start date is", this.state.startDate);