问题描述
我试图随机化每次刷新页面时从 API 收到的结果。我对设置 onload 的方式有点困惑。
这是我的代码
handleRandom = (e) => {
this.getMarvelResponse(null,null,e);
};
componentDidMount() {
const random = Math.floor(Math.random() * 1473);
this.getMarvelResponse(null,this.state.offset);
onload = () => {this.handleRandom(random)}
}
getMarvelResponse = (id,name,offset) => {
getCharacters({
id: id,name: name,offset: offset,}).then(({ characters }) => {
this.setState(
{
characters: characters.filter(
(chr) => !chr.thumbnail.path.match(imageFound)
),selectedCard: null,},() => {
console.log(this.state.characters);
}
);
});
解决方法
您将不得不创建一个函数来对它们进行洗牌。 https://stackoverflow.com/a/12646864/11765805 我从这条评论中得到了这个
function shuffleArray(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;
}
}
你会想在这里调用它
getMarvelResponse = (id,name,offset) => {
getCharacters({
id: id,name: name,offset: offset,}).then(({ characters }) => {
/////////Call Here
this.setState(
{
characters: characters.filter(
(chr) => !chr.thumbnail.path.match(imageFound)
),selectedCard: null,},() => {
console.log(this.state.characters);
}
);
});