简体   繁体   English

ReactJS中的按钮第二次点击后才调用function,第一次点击后没有效果

[英]Button in ReactJS calls the function only after the second click, no effect after the first click

I am building a simple app for visualization of sorting algorithms in ReactJS. Here is my function:我正在 ReactJS 中构建一个用于可视化排序算法的简单应用程序。这是我的 function:

const [HeightsArray, setHeightsArray] = useState([]);
const [Array, setArray] = useState(ArrayList(HeightsArray));
  
  const randomize = ()=>{
    const randomList = RandomHeightsList(ArrayLength);
    setHeightsArray(randomList);
    setArray(ArrayList(HeightsArray));
}

The RandomHeightsList function simply returns an array of random numbers. RandomHeightsList function 只是返回一个随机数数组。

const RandomHeightList = (ArrayLength)=>{
    let randomHeightsArray = [];
    while (randomHeightsArray.length<ArrayLength){
        let randomHeight = Math.round(Math.random()*350);
        randomHeightsArray.push(randomHeight);
    }
    return randomHeightsArray;

The ArrayList function creates an array of elements (divs) where each element has the corresponding height from a given array of heights as shown below: ArrayList function 创建一个元素数组 (divs),其中每个元素都具有给定高度数组中的相应高度,如下所示:

const ArrayList = (heightsArray) => {
    let array = [];
    for (let i=0; i<heightsArray.length; i++){
        array.push(ArrayElement(heightsArray[i]));
    }
    return (
        <div className="array-list">
            {array}
        </div>
    )
}

Finally, Array Element is just a div with some height.最后,Array Element 只是一个具有一定高度的 div。

const ArrayElement = (height) => {
    const baseTop = 300;
    let top = baseTop-height;
    let styleObject = {height: height, top: top};
    return (
        <div className="array-element" style={styleObject}>
        </div>
    )
}

Now here is my simple button:现在这是我的简单按钮:

<button className="randomize-button" onClick={randomize}>Randomize</button>

When I click the button the first time, nothing happens, the array does not get randomized.当我第一次点击按钮时,没有任何反应,数组没有随机化。 However, after that it works well.但是,在那之后它运作良好。 If I click the button the second time it gets randomized.如果我第二次单击该按钮,它将随机化。 If I click it a third time it gets randomized again as it should.如果我第三次单击它,它会再次随机化。 It has no effect the first time.第一次没有效果。 Any help would be appreciated.任何帮助,将不胜感激。

The issue is with these lines in your randomize function:问题在于您的randomize function 中的这些行:

setHeightsArray(randomList);
setArray(ArrayList(HeightsArray));

You are setting the value of HeightsArray and using it right away, but it won't get updated until next render.您正在设置 HeightsArray 的值并立即使用它,但直到下一次渲染它才会更新。 So you need to change the second line to:因此,您需要将第二行更改为:

setArray(ArrayList(randomList));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM