我正在尝试在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
函数代码中,我试图给予需要做什么的想法,但代码显然是不正确的。我会很感激你的帮助
3条答案
按热度按时间xqk2d5yq1#
你可以在得到API的响应后立即打乱数组。
uurv41yg2#
Fischer-Yates shuffle通常是使用的。
看起来你很接近了,但是算法从数组的末尾提取一个随机项,而不是像你这样从数组的开头提取。
tf7tbtn23#