简体   繁体   中英

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:

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.

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:

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.

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:

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. So you need to change the second line to:

setArray(ArrayList(randomList));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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