【发布时间】:2020-03-05 10:14:04
【问题描述】:
我想为我的组件添加“加载”功能。 问题是加载不是异步功能, 所以 setStates 可能会自己批处理。 我们看一下代码:
constructor(props) {
super(props);
this.state = {
loading: false,
myArray: [1,2,3, ... ,500] //pseudo code (i want to say there is 500 elements, not exactly numbers (cuz i have objects) but to illustrate the problem it doesn't matter)
};
}
editTable = (howManyElementsToEdit) => {
if(howManyElementsToEdit > 50) {
// set loading to true (and make react rerender)
this.setState({
loading: true,
})
//after react rerendering (the react knows that is in this specified line number in this method?) i want to do the calculations
const tmp = [...this.state.myArray]; //copy the array
for(let i=0; i<howManyElementsToEdit; i++) {
tmp[i] += 1;
}
//and now after the modification is done, setState again and loading is false
this.setState({
myArray: tmp,
loading: false,
})
} else { //there is no need to loading because not much elements need to be modified
const tmp = [...this.state.myArray]; //copy the array
for(let i=0; i<howManyElementsToEdit; i++) {
tmp[i] += 1;
}
this.setState({
myArray: tmp,
})
}
}
但你可以猜到它不起作用,因为可能会反应“合并”这些 2 个 setStates(当 howManyElementsToEdit > 50 时),这就是为什么我看不到任何加载 当我在渲染中显示 this.state.loading 时。
有人知道我怎样才能实现我的目标吗?
【问题讨论】:
-
为什么是 -1 ?我不明白。
-
-2 ? ……呃,为什么?我只想加载...
标签: javascript reactjs react-native