【问题标题】:function should call only when i reload the page in react函数应该只在我重新加载页面时调用
【发布时间】: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


    【解决方案1】:

    嗯,它应该使用 useEffect Rajat,或者你用错了,让我给你举个例子你可以试试

    useEffect(()=>{
    // your shuffle function
    }, 
    // keep this empty array so it's only triggered on first load only
    [])
    

    希望有用,谢谢

    【讨论】:

      猜你喜欢
      • 2017-09-17
      • 2011-03-28
      • 2012-05-27
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 2017-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多