我制作了一个组件,通过 xhr 在用户上加载数据,选择
这里的问题是 setState
是异步的(在某些情况下可以同步)。这就是为什么你得到以前的值(value)。
有两种可能的解决方案。
//
// 1. use value directly.
//
switchCategory = (ev) => {
this.setState({ currentCategory: ev.target.value });
this.loadData(ev.target.value);
}
loadData = async (currentCategory) => {
console.log(currentCategory);
// Get data via XHR...
}
//
// 2. use completition callback on `setState`.
//
switchCategory = (ev) => {
this.setState({ currentCategory: ev.target.value }, () => {
this.loadData(ev.target.value);
});
}
loadData = async () => {
const { currentCategory } = this.state;
console.log(currentCategory);
// Get data via XHR...
}
同步文章
setState
在 react
[link]