反应地图函数 - 随机返回一个项目



>我有一个数组,我想在我的渲染函数中随机显示数组中的一个项目。这是我现在拥有的显示所有项目的内容:

render() {
return (
<article className="rand-product-cont">
{this.state.products && this.state.products.map((product, index) => (
<article key={index} className="rand-product">
<h3>"{product.name}"</h3>
</article>
))}
</article>
);
};

如何修改它以仅随机显示数组中的一个产品?我根据我发现的另一个问题尝试了这个,但它似乎每次都显示相同的产品:

render() {
const product = this.state.products.sort(() => Math.random() - Math.random()).slice(0, 1);
return (
<article className="rand-product-cont">
{product && product.map((product, index) => (
<article key={index} className="rand-product">
<h3>"{product.name}"</h3>
</article>
))}
</article>
);
};

你的随机生成器就像魅力一样工作。问题在于如何呈现代码从数组中选取的产品products

在不map的情况下尝试以下操作:

render() {
const product = this.state.products.sort(() => Math.random() - Math.random())
.find(() => true);
return (
<article className="rand-product-cont">
{product &&
<article className="rand-product">
<h3>"{product.name}"</h3>
</article>
}
</article>
);
};

上面的解决方案使用与我在这里类似的方法,表示products数组,只有数字值,find返回第一个元素,因此您无需products数组上使用索引器:

const array = [12,23,43,45,34,22,77];
const element = array.sort(() => Math.random() - Math.random())
.find(() => true);
console.log(element);

我希望这有帮助!

如果你只需要一个元素,并且它是随机的。我完全看不出使用地图的意义

function getRandomElFromArray(arrayLenght) {
return Math.floor(Math.random() * arrayLength);
}
<article ...
{
product && product.length > 0 &&
product[getRandomElFromArray(product.length)]
}
</article>

最新更新