我目前正在用React JS创建一个应用程序,并希望根据用户单击的按钮(每个按钮是不同的排序算法)在屏幕上显示动画(对数组进行排序)。问题是我如何在每次按下按钮时就开始设置排序算法,但是如果多次按下,则将在同一阵列上同时发生多个排序算法。
constructor(props)
{
super(props);
this.state = {
array: [],
animating: false
};
//this.onClick = this.onClick.bind(this.state.animating);
}
componentDidMount()
{
this.randomArray();
//this.setState({animating: false});
}
mergeAnimationDecoder(choice)
{
this.setState({animating: true});
console.log(this.state.animating);
const sortingArray = sortingAnimations(this.state.array, choice);
//console.log(sortingAnimationArray);
for(let i = 0; i < sortingArray.length; i++)
{
const arrayBarClass = document.getElementsByClassName('array-bar');
//console.log(arrayBarClass);
const ischangeColor = i % 2 !== 1;
if(ischangeColor)
{
const arrayBarOneIndx = sortingArray[i][0];
const arrayBarTwoIndx = sortingArray[i][1];
//console.log(arrayBarOneIndx);
//console.log(arrayBarTwoIndx);
const arrayBarOneStyle = arrayBarClass[arrayBarOneIndx].style;
const arrayBarTwoStyle = arrayBarClass[arrayBarTwoIndx].style;
setTimeout(() => {
arrayBarOneStyle.backgroundColor = barColorOne;
arrayBarTwoStyle.backgroundColor = barColorTwo;
}, i * sortAnimationSpeed);
setTimeout(() => {
arrayBarOneStyle.backgroundColor = barColorTwo;
arrayBarTwoStyle.backgroundColor = barColorOne;
}, i * sortAnimationSpeed);
}
else
{
setTimeout(() => {
const barCurrentIndx = sortingArray[i][0];
//console.log(barCurrentIndx);
const barCurrentValue = sortingArray[i][1];
//console.log(barCurrentValue);
const barCurrentStyle = arrayBarClass[barCurrentIndx].style;
//console.log(barCurrentStyle);
barCurrentStyle.height =`${barCurrentValue}px`;
}, i * sortAnimationSpeed);
}
}
this.setState({animating: false});
}
render()
{
const array = this.state.array;
return(
<div className='array-container'>
{array.map((value, indx) =>
(<div className = 'array-bar'
key = {indx}
style = {{backgroundColor:barColorOne, height:`${value}px`}}
>
</div>)
)}
<button onClick={() => {if(this.state.animating === false){this.randomArray()}}}>Generate New Array</button>
<button onClick={() => {if(this.state.animating === false){this.mergeAnimationDecoder(0)}}}>Merge Sort</button>
<button onClick={() => {if(this.state.animating === false){this.quickAnimationDecoder(1)}}}>Quick Sort</button>
<button onClick={() => {if(this.state.animating === false){this.heapAnimationDecoder(2)}}}>Heap Sort</button>
<button onClick={() => {if(this.state.animating === false){this.bubbleAnimationDecoder(3)}}}>Bubble Sort</button>
<button onClick={() => {if(this.state.animating === false){this.testSortingAlgorithm()}}}>Check Algorithm</button>
<button onClick={() => console.log(this.state.animating)}>Testing</button>
</div>
);
}
我尝试更改动画的状态,并在按下按钮时使用if语句来确定动画是否仍在发生,但是在算法函数中调用setState时动画的值未更改。我相信这是因为必须重新渲染render函数并接收新的和更新的状态,但是我读到只要调用setState,react就会自动更新依赖该状态的组件和所有函数。