import React, { useContext } from 'react'
import { stockContext } from '../../App.js';
import { Link } from 'react-router-dom';
function Recommend() {
const products = useContext(stockContext);
console.log(products); // 데이터 [{id: 1, title: ABC, price : 300,000...}, {id: 2...}]
let randomArray = [] // 랜덤 id 4개 뽑기
for (let i = 0; i < 4; i++) {
let randomNum = Math.floor(Math.random() * products.length)+1;
if (randomArray.indexOf(randomNum) === -1) {
randomArray.push(randomNum)
} else {
i--
}
}
let getRandomItem1 = products.find((item) => {
return item.id == randomArray[0];
});
let getRandomItem2 = products.find((item) => {
return item.id == randomArray[1];
});
let getRandomItem3 = products.find((item) => {
return item.id == randomArray[2];
});
let getRandomItem4 = products.find((item) => {
return item.id == randomArray[3];
});
return (
<>
<div className="recommendation">
<h3>다른 상품 보여주세요</h3>
<div className="card">
<Link to={'/product/${getRandomItem1.id}'}>
<div>{getRandomItem1.title}</div>
<span>{getRandomItem1.price}</span>
</Link>
</div>
<div className="card">
</div>
<Link to={'/product/${getRandomItem2.id}'}>
<div>{getRandomItem2.title}</div>
<span>{getRandomItem2.price}</span>
</Link>
</div>
</>
)
}
export default Recommend
id 랜덤으로 뽑아서 4개만 보여지는 상품 리스트를 만들고 싶어요
getRandomItem1~4로 만들어서 하나씩 입력하니깐 비효율적인거 같아서
반복문으로 하려고 했는데 계속 실패하고 잘 안돼서 질문드려요 ㅠㅠ
어떤 식으로 코드를 작성하면 될까요??