我试图获得 16 张随机图像,但我得到了 1 张相同的图像。我知道需要对 one => one.number
过滤器进行更改,但尝试失败。
import React from "react";
import { getCard } from "../redux";
import { connect } from "react-redux";
import CardBoard from "./CardBoard";
class Board extends React.Component {
componentDidMount() {
this.props.getCard();
}
render() {
let gameCard = Math.floor(Math.random() * (54 - 2) + 2);
const game = () => {
let cards = [];
if (cards.length < 16) {
cards.push(gameCard);
}
return cards;
};
return (
<div>
{this.props.cards
.filter(one => one.number === gameCard)
.map(card => (
<CardBoard
key={card._id}
id={card._id}
name={card.name}
number={card.number}
imgUrl={card.imgUrl}
/>
))}
</div>
);
}
}
export default connect(
state => state,
{ getCard }
)(Board);
最佳答案
您可以实现一个函数,从提供给您的组件的卡片中随机选择 16 张卡片并使用它们:
function getRandom(arr, n) {
const arrLength = arr.length;
const result = [];
const taken = [];
while (result.length !== n && result.length !== arrLength) {
const random = Math.floor(Math.random() * arrLength);
if (!taken.includes(random)) {
result.push(arr[random]);
taken.push(random);
}
}
return result;
}
class Board extends React.Component {
componentDidMount() {
this.props.getCard();
}
render() {
const cards = getRandom(this.props.cards, 16);
return (
<div>
{cards.map(card => (
<CardBoard
key={card._id}
id={card._id}
name={card.name}
number={card.number}
imgUrl={card.imgUrl}
/>
))}
</div>
);
}
}
关于javascript - 尝试使用 Math.random 和过滤器填充 16 个随机图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51162098/