我有一个数组,我想在渲染函数中随机显示数组中的一项。这是我现在所拥有的显示所有项目的内容:
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);
希望这会有所帮助!
关于javascript - React map 函数 - 随机返回一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59329807/