我只想在调用函数完成后才更改组件的状态。函数包含一个间隔,该间隔在一段时间后结束。我试过使用繁忙-等待,使用等待,但它似乎不适用于我。
这就是我初始化状态的方式
constructor(props){
super(props);
this.state = {
array: [],
status: false
}
}这是我试着做的函数,等待一行完成。
bubble_sort_visualize(){
if(this.state.status === false){
this.setState({status: true});
const arr = this.state.array.slice();
const animations = this.bubble_sort_and_push([], arr);
this.animate(animations);
// need to make it work after animate finishes
this.setState({status: false});
}
}这是我想在另一行开始之前完成的函数。
animate(animations){
const colors = ['blue', 'red', 'bisque', '#80ff80'];
const bars = document.getElementsByClassName("bar");
let i = 0;
const intervalHander = function(){
const animation = animations[i];
const bar1 = bars[animation[0]];
const bar2 = bars[animation[1]];
const color = colors[animation[2]];
changeColor(bar1, bar2, color);
i++;
if(i === animations.length){
window.clearInterval(interval);
}
}
const interval = window.setInterval(intervalHander,0.5);
}因此,基本上,在动画方法执行clearInterval操作之后,我试图更改clearInterval方法中的状态。
发布于 2020-06-05 08:59:33
由于您希望setState在所有动画完成后触发in动画函数(该函数在setInterval中触发执行),因此您需要转换动画才能返回如下承诺
animate(animations){
return new Promise(res => {
const colors = ['blue', 'red', 'bisque', '#80ff80'];
const bars = document.getElementsByClassName("bar");
let i = 0;
const intervalHander = function(){
const animation = animations[i];
const bar1 = bars[animation[0]];
const bar2 = bars[animation[1]];
const color = colors[animation[2]];
changeColor(bar1, bar2, color);
i++;
if(i === animations.length){
window.clearInterval(interval);
res();
}
}
const interval = window.setInterval(intervalHander,0.5);
})
}然后把它当作
async bubble_sort_visualize(){
if(this.state.status === false){
this.setState({status: true});
const arr = this.state.array.slice();
const animations = this.bubble_sort_and_push([], arr);
await this.animate(animations);
this.setState({status: false});
}
}发布于 2020-06-05 09:01:42
这就是我要做的。动画完成后,我将调用该函数。
就像这样:
animate(animations){
const colors = ['blue', 'red', 'bisque', '#80ff80'];
const bars = document.getElementsByClassName("bar");
let i = 0;
const intervalHander = function(){
const animation = animations[i];
const bar1 = bars[animation[0]];
const bar2 = bars[animation[1]];
const color = colors[animation[2]];
changeColor(bar1, bar2, color);
i++;
if(i === animations.length){
window.clearInterval(interval);
this.bubble_sort_visualize()
}
}
const interval = window.setInterval(intervalHander,0.5);
}我假设动画是在i === animations.length完成时完成的
https://stackoverflow.com/questions/62211595
复制相似问题