javascript - 无法在反应中正确洗牌
问题描述
我正在尝试在 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
函数代码中,我试图给出需要做什么的想法,但代码显然不正确。我会很感激你的帮助
解决方案
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] ];
});
推荐阅读
- javascript - 如何在我的 react 应用程序中设置 redux 存储?
- ios - 在 iPad 上设置整页弹出框
- c++ - C++ 中 fread 和 strncpy 中的缓冲区溢出
- mongodb - 如果微服务实例被复制,则更改流复制
- javascript - React 兄弟组件之间的状态泄漏
- amazon-web-services - 为什么我不能创建这个 Route53 CNAME 别名?
- unit-testing - 如何测试多次分派的动作?
- php - 检查数组元素中是否有任何禁止的扩展
- python - python - 绘制隐式函数 f(x,y) = 0,其中 x,y 进行矩阵乘法
- sql - 从 Oracle 数据链路合并时的优化