【问题标题】:unable to shuffle array correctly in react无法在反应中正确洗牌
【发布时间】:2020-11-26 17:48:13
【问题描述】:

我正在尝试对 react 中的数组进行洗牌。我从 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 函数中的代码中,我试图说明需要做什么,但代码显然不正确。非常感谢您的帮助

【问题讨论】:

    标签: javascript reactjs random


    【解决方案1】:

    从 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();
    }, []);
    

    【讨论】:

    • 我想获取一次数据,而不是每次随机播放时都获取数据,因为当我点击一个项目时,数组必须被随机播放
    • 这段代码只会抓取一次,一旦抓取完成就会随机播放一次。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2019-05-25
      • 1970-01-01
      • 2016-04-26
      • 2014-04-27
      • 2021-07-28
      • 2021-10-15
      • 2013-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多