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

home2 게시판 React 게시판 Lifecycle과 useEffect 2 강의 질문있습니다.

Lifecycle과 useEffect 2 강의 질문있습니다.

2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 글쓴이
  • #136019

    22
    참가자
    app.jsx 파일에 <Route path="/detail" element={<Detail shoes={shoes} />} /> 
    이 구문이 있는데도 작동이 안됩니다.
    Uncaught TypeError: Cannot read properties of undefined (reading 'title')
    질문입니다. 
    1. 강의 대로 따라 쳤는데 강의 의도상(Lifecycle과 useEffect 2까지 강의) Detail까지 들어가면 화면에 에러나오는게 맞고 
    Detail/id 로 들어가야지 에러없이 정상적으로 작동되는건가요? 추후 Detail파트 부분을 수정하는 강의가 있는건가요?
    2. gpt 한테 물어보니 Detail.jsx파일에 아래부분을 추가해야 한다는데 추가하면 <div>잘못된 접근입니다.</div>이 부분이 뜹니다.
    function Detail(props) { 
    let { id } = useParams(); // props.shoes가 없는 경우 방지 <-추가
    if (!props.shoes) { return <div>데이터를 불러오는 중입니다...</div>; } // id가 숫자로 변환되지 않으면 예외 처리<-추가 
    if (!id || isNaN(id)) { return <div>잘못된 접근입니다.</div>; }<-추가
    3. 근데 저번 강의 답변에서는 https://codingapple.com/forums/topic/lifesycle-%ec%a7%88%eb%ac%b8%ec%9e%88%ec%8a%b5%eb%8b%88%eb%8b%a4/
          <Route path="/detail" element={<Detail/>}/>
       <Route path="/detail/:id" element={<Detail shoes={shoes} />} />
    위 2개 구문을 넣으라고 하셨습니다. 뭐가 맞는건가요?
    4. 코드 첨부링크 보내니 혹시 확인 부탁드려도 되나요? https://drive.google.com/drive/folders/11lNTGv6zLvy_4jnKu407P7hgWlplICmZ?usp=drive_link
    
    
    app.jsx
    import { Button,Navbar,Container,Nav } from 'react-bootstrap';
    import { useState } from 'react'
    import Row from 'react-bootstrap/Row';
    import Col from 'react-bootstrap/Col';
    import reactLogo from './assets/react.svg'
    import viteLogo from '/vite.svg'
    import './App.css'
    import data from './data.js';
    import { BrowserRouter as Router, Routes, Route, Link,useNavigate,Outlet  } from 'react-router-dom';
    import { use } from 'react';
    import Detail from './routes/Detail.jsx';
    function App() {
      const [count, setCount] = useState(0)
      let [shoes] =useState(data)
      let navigate=useNavigate();
      
      return (
        <>
        <Button variant="primary">Primary</Button>
              <Navbar bg="dark" data-bs-theme="dark" >
            <Container>
              <Navbar.Brand href="#home">Navbar</Navbar.Brand>
              <Nav className="me-auto">
                <Nav.Link href="#home">Home</Nav.Link>
                <Nav.Link onClick={()=>navigate('./')}>Features</Nav.Link>
                <Nav.Link onClick={()=>navigate('/detail')}>detail</Nav.Link>
              </Nav>
            </Container>
          <Link to="/">홈</Link>
          <Link to="/detail">디테일</Link>
          <div className='main-bg'>
            
    </div>
          </Navbar>
     
          <Routes>
          <Route path="/" element={<div>
            <>
            <Container>
          <Row>
            {
            shoes.map(function(a,i){
              return(
                <Card shoes={shoes[i]} i={i+1}>/</Card>
            )
            })}
            <Col sm>쥬탬므</Col>
            <Col sm>치킨</Col>
          </Row>
        </Container>
            </>
          </div>}/>
          
          <Route path="/detail" element={<Detail shoes={shoes} />} />
          <Route path="/detail/:id" element={<Detail shoes={shoes} />} />
          <Route path="*" element={<div>없는페이지에요.</div>}>
          </Route>
     
            
            
      
          </Routes>
          <br />
          
        </>
      )
    }
    function Card(props){
      return(
      <div className="col-md-4">
      < img src={'https://codingapple1.github.io/shop/shoes'+props.i+'.jpg'} width="80%" />
      <h4>{ props.shoes.title }</h4>
      <p>{ props.shoes.price }</p>
    </div>
    )
    }
    export default App
    Detail.jsx
    import{useEffect, useState} from "react";
    import { useParams } from "react-router-dom";
    function Detail(props){
        let{id}=useParams();
        let 찾은상품=props.shoes.find(function(x){
            return x.id==parseInt(id)
        
        })
        let [Alert,setAlert]=useState(true)
        useEffect(()=>{
            let a= setTimeout(() => {
                setAlert(false)
            }, 100000);
            return()=>{clearTimeout(a)}
        },[])
        // return(
        //     <div className="col-md-4">
            
        //         {
        //             Alert==true?<div>초이내구매시할인</div>:setAlert=false
        //         }
        //     </div>
        // );
        // console.log(id);
        return(
            <div className="col-md-4">
            < img src={'https://codingapple1.github.io/shop/shoes'+props.i+'.jpg'} width="80%" />
            <h4>{ props.shoes[id].title }</h4>
            <p>{ props.shoes[id].price }</p>
          </div>
          )
    }
    export default Detail;
    • 이 게시글은 22에 의해 5 월, 1 주 전에 수정됐습니다.
    #136027

    codingapple
    키 마스터
    /detail로 들어가면 id라는 파라미터같은게 없으니 .title 왼쪽이 비어있다고 하는 것일 뿐입니다 
    id 변수에 뭐가 없으면 다른거 보여달라고 if문이나 삼항연산자 같은거 씁시다
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 호 / 개인정보관리자 : 박종흠