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

home2 게시판 React 게시판 useEffect 관련된 질문 드립니다.

useEffect 관련된 질문 드립니다.

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

    조승현
    참가자
    안녕하세요 코드 작성이 어려워 이렇게 코드를 작성해도 문법에 어긋나지 않을지 질문 드립니다.
    setInterval 사용하여 1초 마다 1초씩 줄어들게하여 0초가 되면 clearInterval 주려고 해봤는데,
    이렇게 주는게 맞나요?? 
    
    
    import { useParams } from "react-router-dom";
    import styled from 'styled-components';
    import { useEffect, useState } from 'react';
    let YellowBtn = styled.button`
        background : ${props => props.bg};
        color : ${props => props.bg == 'blue' ? 'white' : 'black'};
        padding : 10px;
    `
    let Box = styled.div`
        background : grey;
        padding : 20px;
    `
    function Detail(props){
        let {id} = useParams();
        let index = props.shoes.findIndex(function(a, b){
            return Number(id) === a.id
        })
        let [time, setTime] = useState(3);
        let [alert, setAlert] = useState(true);
        useEffect(()=>{
            let timer = setInterval(()=>{
                if(time > 0){
                    setTime(time - 1);
                    console.log(time)
                }else if(time === 0){
                    setAlert(false);
                }
            }, 1000)
            return () => {
                clearInterval(timer)
            }
        }, [time])
        // useEffect(()=>{
        //     let a = setTimeout(()=>{
        //         setAlert(false)
        //     }, 2000)
        //     return () => {
        //         clearTimeout(a)
        //     }
        // }, [])
        return (
            <div className="container">
                {/* <Box><YellowBtn bg="blue">버튼</YellowBtn></Box> */}
                { alert === true ? <div className="alert alert-warning">{time}초 후에 닫힙니다.</div> : null }
                <div className="row">
                    <div className="col-md-6">
                    < img src={`https://codingapple1.github.io/shop/shoes${props.shoes[index].id + 1}.jpg`} alt="상품목록" width="100%" />
                    </div>
                    <div className="col-md-6">
                    <h4 className="pt-5">{props.shoes[index].title}</h4>
                    <p>{props.shoes[index].content}</p>
                    <p>{props.shoes[index].price}</p>
                    <button className="btn btn-danger">주문하기</button>
                    </div>
                </div>
            </div>
        )
    }
    export default Detail
    #66998

    codingapple
    키 마스터
    time이 변경될 때 마다 useEffect안의 코드가 실행되니까 time바뀌면 매번 타이머도 재생성될거같긴합니다
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 호 / 개인정보관리자 : 박종흠