![](/img/trans.png)
[英]React - this.setState doesn't work as expected until function is called a second time
[英]setState doesn't work as expected. It takes the initial state each time time
所以我有这个代码片段,每次单击按钮时我都必须更新 state 并调用 api。 第一次它按预期工作,但下一次它将 endTime 设置为初始时间并将 startTime 设置为比预期早 2 小时。 我的控制台日志运行良好,但在我尝试设置状态时出现了一些问题。 我尝试在每个 setState 之后添加一个回调 function 并尝试在 if-else 结束后设置 state 但它没有显示所需的结果。
class ButtonComponent extends Component{
constructor(props) {
super(props);
this.state = {
timeData: {
endTime: moment(),
startTime: moment().subtract(2, 'h'),
},
dropdownOption: '2HOURS'
}
this.callAPI= this.callAPI.bind(this);
}
componentDidMount() {
if (this.state.dropdownOption=== '2HOURS') {
this.callAPI();
}
}
onClick(){
let time = {...this.state.timeData};
let option;
option = this.state.dropdownOption;
if(option === '10hours'){
time['endTime'] =timeData['startTime'];
console.log('endTime', timeData['endTime'])
time['startTime'] = timeData['endTime'].subtract(10, 'h');
console.log('startTime', time['startTime'])
this.setState({timeData: time}, this.callAPI())
}
}
}
}
我不确定你想做什么,但是,你应该注意setState
是异步的,所以如果你在调用setState
的同时调用callAPI
,那么callAPI
没有得到更新的 state 是正常的。(我想我明白这是您尝试使用callAPI
的方式)。
这是一个实施建议,至少是为了让它更清楚:
class ButtonComponent extends Component{
constructor(props) {
super(props);
this.state = {
timeData: {
endTime: moment(),
startTime: moment().subtract(2, 'h'),
},
dropdownOption: '2HOURS',
};
this.callAPI= this.callAPI.bind(this);
}
componentDidMount() {
if (this.state.dropdownOption=== '2HOURS') {
this.callAPI();
}
}
callAPI() {
console.log("updated state", this.state.timedata)
}
onClick() {
const timeData = {...this.state.timeData};
const option = this.state.dropdownOption;
if(option === '10hours') {
// I quite don't get the way you want to update your state so this might need to be adapted.
timeData.endTime = timeData.startTime;
timeData.startTime = moment();
// this.callAPI willl be called as soon as the state update is resolved by setState so the new state will be available inside callAPI.
this.setState({timeData}, this.callAPI);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.