javascript 无法在react中正确混洗数组

uplii1fm  于 2023-04-28  发布在  Java
关注(0)|答案(3)|浏览(163)

我正在尝试在react中 Shuffle 。我从API中获取数据,然后我想在屏幕上将数据图片作为一个混洗数组装入,而不是按照我获取它们的顺序。
这是我的代码:
useFetch.js

import {React , useState , useEffect} from 'react';

export default function useFetch() {
  
  const [ pokemon,setPokemon] = useState([]);
  const [shuffled,setShuffled]= useState([]);
  useEffect(()=>{
    const fetchPokemon = async () =>{  //here I fetch my pokemon 
      const promises = [];
      for (let i=1;i<=10;i++){
        let  url = `https://pokeapi.co/api/v2/pokemon/${i}`;
        let response = await fetch(url);
        let result = await response.json();
        promises.push(result);
      }

      const data = await Promise.all(promises);
      setPokemon(...pokemon,data); //successfully sets the pokemon data 
    }

    const shufflePokemon = ()=>{ //here I try to shuffle the pokemon array and return a random on mount 
      fetchPokemon(); 
      let randomArray= pokemon.map((poke,index)=>{ //this is what I am trying to do to shuffle the array  but it is not correct 
         let  j = Math.floor(Math.random() * (index + 1)); 
         let temp = poke[index];
         poke[index] = poke[j];
         poke[j] = temp;
      })
      setShuffled(...shuffled,randomArray);

    }

    shufflePokemon(); //call shuffle on mount 
  },[])
 
   return {shuffled} //returns shuffled array of objects 

}

在上面的shufflePokemon函数代码中,我试图给予需要做什么的想法,但代码显然是不正确的。我会很感激你的帮助

xqk2d5yq

xqk2d5yq1#

你可以在得到API的响应后立即打乱数组。

useEffect(() => {
  const shuffle = (array) => {
    for (var i = array.length - 1; i > 0; i--) {
      var j = Math.floor(Math.random() * (i + 1));
      var temp = array[i];
      array[i] = array[j];
      array[j] = temp;
    }
  };

  const fetchPokemon = async () => {
    //here I fetch my pokemon
    const promises = [];
    for (let i = 1; i <= 10; i++) {
      let url = `https://pokeapi.co/api/v2/pokemon/${i}`;
      let response = await fetch(url);
      let result = await response.json();
      promises.push(result);
    }

    const data = await Promise.all(promises);
    shuffle(data);
    setPokemon(data);
  };

  fetchPokemon();
}, []);
uurv41yg

uurv41yg2#

Fischer-Yates shuffle通常是使用的。
看起来你很接近了,但是算法从数组的末尾提取一个随机项,而不是像你这样从数组的开头提取。

const randomArray = Array.from(fetchPokemon()).forEach((v,i,a) => {
  const r = a.length - 1 - Math.trunc(Math.random() * i);
  [ a[i], a[r] ] = [ a[r], a[i] ];
});
tf7tbtn2

tf7tbtn23#

let array= ['dokan', 'Machine Learning', 'Data Science', 'Metaverse', 'Crypto', 'Tech']
list = array.sort(() => Math.random() - 0.5)

相关问题