[React] 부족한 JS문법 정리

youngseo·2022년 7월 29일
0

REACT

목록 보기
25/52
post-thumbnail

1. forEach 대신 map

function App() {

  return (
    <div>
      {data.forEach(d => (
        <Board data={d} />
      ))}
    </div>
  );
}

export default App;

위 코드와 같이 forEach를 써서 순회하며 자식태그로 props를 보낼 수는 없다. forEach는 반환을 하지 않기 때문에 map을 사용해야한다.

2. reduce

2-1

const data = [
  {'id': 1, 'title': '제목1', 'content': '내용1', 'category':'영화'},
  {'id': 2, 'title': '제목2', 'content': '내용2', 'category':'드라마'},
  {'id': 3, 'title': '제목3', 'content': '내용3', 'category':'예능'},
]

위와 같은 데이터를 카테고리별로 구분해 관리를 하고 싶은 경우, reduce를 이용할 수 있다.

const result = data.reduce((acc, cur) => {
    //만약 카테고리를 가지고 있다면, 배열에 추가
    if(cur.hasOwnProperty(cur.category)){
      return {
        ...acc,
        [cur.category]: [...acc[cur.category], cur]
      }
    } else {
      //새로운 카테고리 key를 생성하고 배열도 추가
      return {
        ...acc,
        [cur.category] : [cur]
      }
    }
  }, {})

  /**
   * result= {
   *   '영화' : [{'id': 1, 'title': '제목1', 'content': '내용1', 'category':'영화'}],
   *   '드라마' : [{'id': 2, 'title': '제목2', 'content': '내용2', 'category':'드라마'}],
   *   '예능' : [{'id': 3, 'title': '제목3', 'content': '내용3', 'category':'예능'}]
   * } 
   * 
   */

+ PLUS

각 카테고리별 이름을 조회하는 방법 전체코드

const keys = Object.keys(result)

 return (
    <table>
      <thead>
        <tr style={{fontWeight : "bold"}}>
          <td>Name</td>
          <td>Price</td>
        </tr>
      </thead>
      <tbody>
      {keys.map((key, index) => 
        <ProductsTable 
          category={key} 
          items={result[key]} 
          key={index} 
          inStockOnly= {filter.inStockOnly}/>
        )}
      </tbody>
    </table>
  )
}

+plus

data.reduce((acc,cur) => acc + cur.title + ', ', '')
//'제목1, 제목2, 제목3, '

2-2 장바구니에 담긴 아이템의 총수량 체크

function HeaderCardButton(props) {
  const cartCtx = useContext(CartContex)
  const numberOfCartItems = cartCtx.items.reduce((curNumber, item) => {
    return curNumber + item.amount
  }, 0)

3. concat

import React, {useEffect, useState} from 'react'

function Loading() {
  const [isLoaded, setIsLoaded] = useState(false)
  const [text, setText] = useState([])

  useEffect(()=>{
    //컴포넌트가 렌더링될 때 실행될 함수
    //데이터 갖고오기 요청보내고, 데이터가 오면 isLoaded = true
    setTimeout(() => {
      setIsLoaded(true)
    },3000)
  }, [])

  useEffect(() => {
    setText(text.contain(['추가']))}, [isLoaded])

  return (
    <div>
      {isLoaded ? <>로딩완료!</> : <>로딩 중</>}
    </div>
  )
}

export default Loading

push대신 위와 같이 concat을 이용해 로직을 작성할 수도 있습니다.

0개의 댓글