mock data로 만든 값을 진짜로 서버에서 보내준 값으로 바꾸기 위해서는 1.정확한 key이름과 2.위치 (어느배열안에 위디에 위치하고 있는지)를 적어줘야한다.
먼저, 서버에서 보내준 값을 보고 -> 그 값을 fetch해서 map돌리는 곳에서 이름을 변경해주면 된다.
- 먼저 서버에서 값을 받는다
- 개발자도구 - network 에 들어가서 보내준 값을 본다
보내준 값들중에서 받으려는 값을 찾아서 key값이 무엇으로 되어있는지를 찾는다.
예를 들어 이미지를 받고자하면,
message - products - products_detail - [0] - image_url
의 경로의 키값을 확인한다
[
{
"id": 1,
"img": "/images/Aesop_Tacit_Eau_de_Parfum.png",
"name": "테싯 오 드 퍼퓸",
"feature_name": "상쾌한, 그린, 시트러스향"
},
{
"id": 2,
"img": "/images/Aesop_Tacit_Eau_de_Parfum.png",
"name": "테싯 오 드 퍼퓸",
"feature_name": "상쾌한, 그린, 시트러스향"
},
{
"id": 3,
"img": "/images/Aesop_Tacit_Eau_de_Parfum.png",
"name": "테싯 오 드 퍼퓸",
"feature_name": "상쾌한, 그린, 시트러스향"
},
{
"id": 4,
"img": "/images/Aesop_Tacit_Eau_de_Parfum.png",
"name": "테싯 오 드 퍼퓸",
"feature_name": "상쾌한, 그린, 시트러스향"
},
{
"id": 5,
"img": "/images/Aesop_Tacit_Eau_de_Parfum.png",
"name": "테싯 오 드 퍼퓸",
"feature_name": "상쾌한, 그린, 시트러스향"
}
]
const [items, setItems] = useState({});
{Items.map(({ id, img, name, feature_name }) => {
return (
<ItemCard
key={id}
itemPhoto={img}
itemName={name}
itemDescription={feature_name}
/>
key값을 임의적으로 넣어주었다. 이것들을 실제로 받은 서버와 비교한뒤, js에서 키와 경로를 정확하게 적어주면 된다.
아래의 실제 서버에서 받은 data를 바탕으로 바꿔주면 되는데 밖에서부터 차근차근들어간다.
백엔드와 이야기해봐서 내가 받아와야할값은 product_id, image_url,product_name,content 이렇게 4개.
js의 map안에서 위의 값들의 경로를 세세하게 적으면 끝난다.
예를들어 product_id는 message안의 products안의 product_id
이걸 코드로 바꾸면
items.message.map(({ products }) => { return ( <ItemCard key={products.product_id}
- map 자체를 items.message로 바꾼다
- products.product_id (product안에 있는 product_id)
나머지값들도 다 이렇게 바꿔준다
{
"message": [
{
"products": {
"product_id": 1,
"product_name": "리무브",
"category_id": 1,
"category_name": "클렌저",
"product_detail": [
{
"product_option_id": 1,
"size_mL": "60",
"price": "27000.000",
"image_url": "https://velog.velcdn.com/images/jiminnote/post/fafd5ab2-3260-49e9-99c5-85a4bda2bfad/image.png"
}
],
"product_feature": [
{
"id": 1,
"feature": "피부타입",
"content": "모든 피부, 메이크업을 한 피부"
},
{
"id": 2,
"feature": "사용감",
"content": "진정된, 생기있는"
},
{
"id": 3,
"feature": "주요 성분",
"content": "그레이프 씨드, 토코페롤, 마트리카리아꽃오일(블루 카모마일)"
}
]
}
},
이러한 값들이 20개 반복
{Object.keys(items).length > 0 &&
items.message.map(({ products }) => {
return (
<ItemCard
key={products.product_id}
itemPhoto={products.product_detail[0].image_url}
itemName={products.product_name}
itemDescription={
products.product_feature[2] &&
products.product_feature[2].content
}
/>
);
})}
Object.keys()를 이용하면 키값들만 뽑아낼 수 있다 https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
products.product_feature[2] &&을 넣는 이유: "이값이 true일때만 실행하세요!"의미
이걸 안넣고 그냥 쓰면 products.product_feature[2].content안에 undefined 값이 있으면 에러가 난다. 그래서 안이 undefined가 아니라 true일때만 실행하라는 조건을 같이 적어주어야한다.