【发布时间】:2022-12-17 23:02:35
【问题描述】:
当我更新它的渲染状态并且我的数组被洗牌时,我不希望这个洗牌功能调用发生在 bcoz 上。我希望仅在重新加载时对数组进行洗牌,但使用 useEffect 不会解决问题,它会使我的数组不洗牌
import { useEffect } from "react";
import { useCallback } from "react";
import { useState } from "react";
import audi from "./images/audi.jpg";
import blackcar from "./images/carinblack.jpg";
import ferrari from "./images/ferrari.jpg";
import lambo from "./images/lambo.jpg";
import rangerover from "./images/rangerover.jpg";
export const Robot = () => {
const [display,setDisplay]=useState('none')
let array = [audi, blackcar, ferrari, lambo, rangerover,audi];
function shuffle(array) {
let currentIndex = array.length,
randomIndex;
// While there remain elements to shuffle.
while (currentIndex != 0) {
// Pick a remaining element.
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex],
array[currentIndex],
];
}
return array;
}
shuffle(array)
const handle=()=>{
setDisplay('inline')
}
const Reset=()=>{
setDisplay('none')
}
return (
<>
{array.map((data,index)=>{
return (<>
<img onClick={handle} src={data}/>
</>)
})}
<h3>
Please click on the identical tiles to verify that you are not a robot
</h3>
<button id='reset' style={{display : display}} onClick={Reset}>Reset</button>
</>
);
};
我尝试了 useEffect 但随后重新洗牌数组没有被洗牌
【问题讨论】:
标签: reactjs