• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 React 게시판 쇼핑몰 Detail 연결시 오류

쇼핑몰 Detail 연결시 오류

  • 이 주제에는 1개 답변, 1명 참여가 있으며 berry2 년, 6 월 전에 전에 마지막으로 업데이트했습니다.
2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 글쓴이
  • #64559

    berry
    참가자
    안녕하세요
    
    메인을 보여주는 Main 컴포넌트
    상세페이지인 Detail 컴포넌트
    두개를 routes 폴더에 따로 관리하고 있었는데요
    
    오늘 새로 진도 나간 부분 중 새로운 상품 데이터를 axios로 받아오는 부분이 잘 안풀려서
    Main 컴포넌트를 App.js 안으로 옮겨서 써주고 합쳤습니다
    그런데 제가 Detail Route 코드나 Detail.js를 건들지 않았는데 다음과 같은 오류가 뜹니다 ㅠ
    
    
    
    어제까지는 Detail 페이지가 잘 동작했으니 App.js에서 뭔가 잘못 건들인 것 같은데 어딘지 도통 모르겠습니다 ㅠㅠ
    코드 한 번만 봐주실 수 있을까요?
    
    App.js
    
    
    import './App.css';
    import { useState } from 'react'
    import { Nav, Navbar, Container, Button } from 'react-bootstrap'
    import { Routes, Route, useNavigate } from "react-router-dom";
    import axios from 'axios'
    import data from './data.js'
    import Detail from './routes/Detail.js'
    function App() {
      let [shoes, setShoes] = useState(data)
      const navigate = useNavigate();
      // ^ 메인 UI
      function Main({shoes}) {
        // 상품 더 보기 GET
        function getdata() {
          axios.get('https://codingapple1.github.io/shop/data2.json')
            .then((res) => { 
              let copy = [...shoes, ...res.data]
              setShoes(copy)
              console.log(copy)
            })
            .catch((err) => { console.log('실패함 ㅅㄱ')})
        }
        return (
          <>
            <div className="main-bg"></div>
            <div className="container">
              <div className="row">
                { shoes.map((shoes,i) => {
                  return (
                    <div
                      className="col-md-4"
                      onClick={() => navigate(`/detail/${+i}`)}
                    >
                      < img src={`https://codingapple1.github.io/shop/shoes${i+1}.jpg`} width="80%" alt=""/>
                      <h4>{shoes.title}</h4>
                      <p>{shoes.price}</p>
                    </div>
                  )})
                }
              </div>
            </div>
            <Button variant="outline-secondary" onClick={getdata}>더 보기</Button>
          </>
        )
      }
      // ^ App
      return (
        <div className="App">
          <Navbar bg="dark" variant="dark">
            <Container>
              <Navbar.Brand href="#home">J-Market</Navbar.Brand>
              <Nav className="me-auto">
                <Nav.Link onClick={() => {navigate('/')}}>HOME</Nav.Link>
                <Nav.Link onClick={() => {navigate('/detail')}}>DETAIL</Nav.Link>
                <Nav.Link onClick={() => {navigate('/event')}}>EVENT</Nav.Link>
              </Nav>
            </Container>
          </Navbar>
          <Routes>
            <Route path="/" element={<Main shoes={shoes} />} />
            <Route path="*" element={<p>404</p>} />
            <Route path="/detail/:id" element={<Detail shoes={shoes}/>} />
          </Routes>
          
        </div>
      );
    }
    export default App;
    
    
    Detail.js
    
    
    import { useEffect, useState } from 'react'
    import { useParams } from 'react-router-dom'
    const Detail = ({shoes}) => {
      // input
      const [num, setNum] = useState('')
      useEffect(() => {
        if (isNaN(num) === true) {
          alert('그러지마세요🙄')
          console.log('string')
        }
      }, [num])
      // url 파라미터 id와 상품 고유 id가 같은 지 체크
      const {id} = useParams()
      const shoe = shoes.find((x) => x.id === id)
      // 2초 뒤 사라지는 알럿
      let [saleAlert, setSaleAlert] = useState(true)
      useEffect(() => {
        let timesale = setTimeout(() => setSaleAlert(false), 2000)
        return () => {
          clearTimeout(timesale)
        }
      }, [])
      return (
        <div className="container">
          {
            saleAlert === true ?
              <div className="alert alert-warning">
                2초 이내 구매시 할인!
              </div> :
              null
          }
          <div className="row">
            <div className="col-md-6">
              < img src={`https://codingapple1.github.io/shop/shoes${shoe.id+1}.jpg`} width="100%" />
            </div>
            <div className="col-md-6">
              <h4 className="pt-5">{shoe.title}</h4>
              <p>{shoe.content}</p>
              <p>{shoe.price}</p>
              <input
                className="input"
                value={num || ""}
                onChange={(e) => setNum(e.target.value)}
              /><br/>
              <button className="btn btn-danger">주문하기</button> 
            </div>
          </div>
        </div>
      )
    }
    export default Detail
    
    
    
    
    #64561

    berry
    참가자
    아이고
    Detail 컴포넌트에서
    const shoe = shoes.find((x) => x.id == id)
    이렇게 수정해주니까 되네요 ㅠㅠ
    터미널에서 ==를 ===이렇게 쓰라고 warning 같은게 떴었어서 아무 생각없이 고쳤었는데 그 부분이 문제였던 거 같습니다ㅠ
    
    
2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관, 개인정보처리방침
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠