2 글 보임 - 1 에서 2 까지 (총 2 중에서)
-
글쓴이글
-
2023년 2월 5일 20:49 #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
2023년 2월 6일 09:49 #66998
codingapple키 마스터time이 변경될 때 마다 useEffect안의 코드가 실행되니까 time바뀌면 매번 타이머도 재생성될거같긴합니다
-
글쓴이글
2 글 보임 - 1 에서 2 까지 (총 2 중에서)
- 답변은 로그인 후 가능합니다.