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

home2 게시판 React 게시판 localStorage로 만드는 최근 본 상품 기능

localStorage로 만드는 최근 본 상품 기능

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

    박땡땡
    참가자
    App.js
    
    
    
    /* eslint-disable */
    import { useEffect, useState } from 'react';
    import { Button, Navbar, Container, Nav, Row, Col} from 'react-bootstrap';
    import bg from './bg.png';
    import './App.css';
    /* import a from './data.js' */
    /* import {a, b} from './data.js' */
    import data from './data.js'
    import {Detail} from './pages/Detail.js';
    import {Routes, Route, Link, useNavigate, Outlet} from 'react-router-dom'
    import axios from 'axios'; 
    import Card from './component/Card.js'
    import Cart from './component/Cart.js'
    //import {RecentlyItem} from './component/RecentlyItems.js'
    function App() {
    let [shoes, setShoes] = useState(data);
    let navigate = useNavigate();
    let [moreBtn, setMoreBtn] = useState(0);
    let [loading, setLoading] = useState(false);
    let [noitem, setItem] = useState(false);
    useEffect(()=> {
     
    if(localStorage.getItem('watched') === null) {
    localStorage.setItem('watched', JSON.stringify( [] ));
     }
     }, [])
    return (
    <div className="App">
    <Navbar bg="dark" variant="dark">
    <Container>
    <Navbar.Brand onClick={()=>{ navigate('/') }}>ShoeShop</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('/cart') }}>Cart</Nav.Link>
    </Nav>
    {/* <Nav className="ms-auto">반가워요 kim</Nav> */}
    </Container>
    </Navbar>
    <Routes>
    <Route path="/" element={
    <>
    <RecentlyItem shoes={shoes} />
    <div className="main-bg" style={{ backgroundImage: `url(${bg})` }}></div>
    <div className="container">
    <div className="row">
    <Card shoes={shoes}></Card>
    </div>
    </div>
    {
    loading == true ? <Loading></Loading> : null
    }
    {
    noitem == true? <NoItem></NoItem> : null
    }
    <button onClick={(e)=>{
    setLoading(true);
    if(moreBtn == 0) {
    axios.get('https://codingapple1.github.io/shop/data2.json')
    .then((result)=>{ 
    setLoading(false);
    let copyShoes = [...shoes];
    copyShoes.push(...result.data);
    setShoes(copyShoes);
     }).catch(()=> {
    console.log('데이터 가져오기 실패');
     });
    setMoreBtn(moreBtn+1);
     } else if(moreBtn == 1) {
    axios.get('https://codingapple1.github.io/shop/data3.json')
    .then((result)=>{ 
    setLoading(false);
    let copyShoes = [...shoes];
    copyShoes.push(...result.data);
    setShoes(copyShoes);
     }).catch(()=> {
    console.log('데이터 가져오기 실패');
     });
    setMoreBtn(moreBtn+1);
     } else {
    setLoading(false);
    setItem(true);
     }
    moreBtn >= 2 ? e.target.style.display = 'none' : null;
     }}>더보기</button>
     
    </>
    } />
    <Route path="/detail/:id" element={<Detail shoes={shoes}/>} />
    <Route path="/cart" element={ <Cart/>}/>
    <Route path="*" element={<div>없는 페이지 입니다.</div>} />
    </Routes>
     
    </div>
     );
    }
    function RecentlyItem(props){
    let recentlyStorage = JSON.parse(localStorage.getItem('watched'));
    let shoesList = props.shoes;
    return(
    <div className="recently-item-list">
    <p>최근 본 상품</p>
    {
    recentlyStorage.map((a, i)=>{
    return(
    <div className="recently-item" key={i}>
    <img src={`https://codingapple1.github.io/shop/shoes${a+1}.jpg`} onClick={()=>{ navigate('/detail/'+a) }} width="80%"/>
    <p>{shoesList[a].title}</p>
    </div>
     )
     })
    }
    </div>
     )
    }
     
    function Loading(){
    return(
    <>
    <p>상품 목록을 불러오고 있습니다.</p>
    </>
     )
    }
    function NoItem(){
    return(
    <>
    <p>더 이상 상품이 존재하지 않습니다.</p>
    </>
     )
    }
    export default App;
    
    ----
    선생님 위와같이 최근 본 상품 기능을 만들었는데,
    RecentlyItem 컴포넌트를 불러오지 않은 상태로 npm run start 를 한 뒤에  RecentlyItem 컴포넌트를 불러오면 정상적으로 화면이 보여지나,
    RecentlyItem 컴포넌트를 불러온 상태로 npm run start를 하면 화면이 렌더링 되지 않습니다.
    에러에 대해서 검색해봤는데 원인을 찾지 못하여 이렇게 질문 드립니다 ㅠ
    npm run start 렌더링 과정에서  문제가 생기는 것 같은데 이유를 모르겠습니다 ㅠㅠ..
    
    
    
    
    
    		
    	
    #47118

    박땡땡
    참가자
    recentltyItem 컴포넌트를 불러오지 않고 npm run start를 하면 정상적으로 렌더링 됩니다.
    npm run start 후 recentlyItem 컴포넌트를 불러와도 마찬가지로 문제가 생기지 않습니다.
    
    
    
    하지만 터미널 종료 후 쿠키 삭제 한 뒤 
    재시작 하면 App.js 자체가 렌더링 되지 않는데 ㅠㅠ 왜이럴까요?
    #47161

    codingapple
    키 마스터
    recentlyStorage 에 뭐가 있으면 .map하라고 if문을 추가합시다
3 글 보임 - 1 에서 3 까지 (총 3 중에서)
  • 답변은 로그인 후 가능합니다.

About

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

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

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