这就是我的状态
的样子:
constructor(props, context) {
super(props, context);
this.state = {
show: false,
btnLabel: 'GO!',
car: {
owner: false,
manufacturer: false,
color: false
}
};
}
这就是我修改状态
的方式:
handleClickFetchPrice() {
this.setState({btnLabel: 'Fetching data...' });
console.log(this.state.fetchPriceBtn);
const url = 'some url';
axios.get(url)
.then(res => {
let car = [...this.state.car];
car.owner = res.data.owner;
car.manufacturer = res.data.manufacturer;
car.color = res.data.color;
this.setState({car});
})
}
属性 car
已更新,但 fetchPriceBtn
未更新 - console.log(this.state.fetchPriceBtn);
的输出为仍然开始!
。
我忽略了什么?为什么 fetchPriceBtn
没有更新?
最佳答案
React setState
是一个异步过程 - 你不知道确切的更新时间,你只能安排更新。
要实现所需的功能,您可以向 setState
方法提供回调。
this.setState({ btnLabel: 'Fetching data...' }, () => console.log(this.state.fetchPriceBtn))
您可以了解更多following the documentation关于方法。
关于javascript - ReactJS - 如何更新嵌套和 "normal"状态属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50897997/