ballang React 개인 프로젝트

강준호·2024년 2월 4일

리액트

목록 보기
8/18

1.

오류 발생

goods.map is not a function
TypeError: goods.map is not a function
    at GoodsList (http://localhost:3001/static/js/bundle.js:335:23)
                   ..

해결

//goods.api.js
const getAllGoods = async () => {
  const response = await fetch(endpoint, options);
  const data = await response.json();
  console.log(data);
  return data;
};

//HomePage.js

useEffect(() => {
    api.goods.getAllGoods().then(data => {
      setGoods(data);
    })
}, []);

  //기존 useEffect 코드
    // setGoods(api.goods.getAllGoods());


Promise 반환된것을 Map 으로 받으려고 했던게 문제였던것!

  • getAllGoods와 같은 async 함수 내에서 await를 사용하면 Promise가 해결될 때까지 기다리고 해결된 값을 반환합니다. 그러나 async 함수 컨텍스트 외부에서 getAllGoods를 호출하면(예: async가 없는 useEffect에서) Promise가 해결될 때까지 기다리지 않고 대신 Promise 자체를 수신하게 됩니다.
  • setGoods(api.goods.getAllGoods())를 사용하면 해결된 배열이 아닌 goods에 Promise가 직접 할당됩니다. 그렇기 때문에 .then()을 사용하여 Promise를 처리하고 해결된 데이터로 상태를 업데이트해야 합니다. 이렇게 하면 Promise r이 실행되면 '상품'이 실제 데이터로 설정됩니다.

"/" 경로 HomePage

2. 상품 상세페이지

리액트 라우터 설치

npm install react-router-dom

useParams 란?

  • 라우터에서 파라미터 값을 사용할 수 있게하는 것
//App.js
function App() {
  return (
    <Routes>
      <Route path="/" element={<HomePage />} />
      <Route path="/goods/:goodId" element={<ProductDetailPage />} />
    </Routes>
  );
}


//ProductDetailPage.js
const { itemId } = useParams();

헤더


장바구니에 담기

redux 사용하기


map 주의하기

  {goods.map((good, index) => (
          <li
            key={good.goodsno}
            className="border border-gray-200 rounded-lg overflow-hidden"
          >
            <img
              src={good.img_i}
              alt={good.goodsnm}
              className="w-full h-auto mb-2"
            />
  • map 의 괄호 주의하기 =>{} 아니고 =>()

0개의 댓글