【发布时间】: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