首页 > 解决方案 > 无法在反应中正确洗牌

问题描述

我正在尝试在 react 中对数组进行洗牌。我从 api 获取数据,然后我想将数据图片作为一个随机排列的数组安装在我的屏幕上,而不是按照我获取它们的顺序。

这是我的代码:

使用Fetch.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函数代码中,我试图给出需要做什么的想法,但代码显然不正确。我会很感激你的帮助

标签: javascriptreactjsrandom

解决方案


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] ];
});

推荐阅读