묻고 답해요
161만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
mongoDB 데이터 확인하는 법
강사님께서 mongoDB Clusters 카테고리 들어가면 데이터 확인하실 수 있는데, 저는 따로 뜨는게 없고 이런 화면이 나오네요. 어디서 볼 수 있나요?
-
미해결Next + React Query로 SNS 서비스 만들기
로그인후 replace가 안되는 이유?
지금 로그인 후 핸들러에서 값을 잘 주는것을 확인했고auth.ts의콘솔 부분에 값이 잘 나오는것을 확인했습니다여기서 result에서도 성공했다고 나오는데 replace가 안되네요이유가 뭘까요
-
미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
postman 에러
안녕하세요. 현재 7강 듣고 있는데요, node.js run하고 postman에 이름, 이메일, 패스워드 넣어서 요청하면 에러 뜨고 종료가 됩니다... 이유가 뭔가요?
-
미해결코드로 배우는 React 19 with 스프링부트 API서버
세션5 상품 목록 컴포넌트 처리
import axios from "axios" import { API_SERVER_HOST } from "./todoApi" // api server host const host = `${API_SERVER_HOST}/api/products` // 외부 보낼것 만들기 비동기 통신 export const postAdd = async (product) => { // 객체지정 const header = {headers: {'Content-Type':'multipart/form-data'}} // product와 header 같이 보내기 const res = await axios.post(`${host}/`, product, header) return res.data } export const getList = async (pageParam) => { try{ const {page, size} = pageParam const res = await axios.get(`${host}/list`, {params: {page:page, size:size}}) return res.data } catch (error) { console.error('Error in getList:', error); throw error; } }productsApi.js 위 코드이고 import React, { useState, useEffect } from 'react'; import useCustomMove from '../../hooks/useCustomMove'; import { API_SERVER_HOST } from '../../api/todoApi'; import { getList } from '../../api/productsApi'; const initState = { dtoList: [], pageNumList: [], pageRequestDTO: null, prev: false, next: false, prevPage: 0, nextPage: 0, current: 0 } // 서버에 주소가 바뀌면 상수값만 바꿔줄려고 선언한것 const host = API_SERVER_HOST function ListComponent(props) { // 커스텀 훅 사용해서 이동 refresh: 갱신 const {moveToList, moveToRead, page, size, refresh} = useCustomMove() // 목록 데이터 가져오기 const [serverData, setServerData] = useState(initState) // 데이터 가져오기 const [fetching, setFetching] = useState(false) useEffect(() => { setFetching(true) // 데이터 가져오는 중 자동으로 처리되기 때문에 // 서버데이터가 처리가 되면 getList({page,size}).then(data => { console.log("data>>>>>>>", data); setFetching(false) setServerData(data) }) }, [page,size,refresh]); return ( <div className="border-2 border-blue-100 mt-10 mr-2 ml-2"> {/* fetching일때는 FetchingModal 호출하고 그렇지 않으면 아무것도 안보여준다. */} {fetching? <FetchingModal/> :<></>} <div className="flex flex-wrap mx-auto p-6"> {serverData.dtoList.map(product => <div key= {product.pno} className="w-1/2 p-1 rounded shadow-md border-2" onClick={() => moveToRead(product.pno)} /* 링크 만들어주고 썸네일 이미지 만들어서 보여주는 기능 */ > <div className="flex flex-col h-full"> <div className="font-extrabold text-2xl p-2 w-full ">{product.pno}</div> <div className="text-1xl m-1 p-2 w-full flex flex-col"> <div className="w-full overflow-hidden "> <img alt="product" className="m-auto rounded-md w-60" src={`${host}/api/products/view/s_${product.uploadFileNames[0]}`} /> </div> <div className="bottom-0 font-extrabold bg-white"> <div className="text-center p-1"> 이름: {product.pname} </div> <div className="text-center p-1"> 가격: {product.price} </div> </div> </div> </div> </div> )} </div> </div> ); } export default ListComponent;ListComponent.js 파일인데 import React from 'react'; import ListComponent from '../../components/products/ListComponent'; function ListPage(props) { return ( <div className="p-4 w-full bg-white"> <div className="text-3xl font-extrabold"> Products List Page </div> <ListComponent/> </div> ); } export default ListPage;ListPage.js 파일입니다 터미널에 에러도 뜨지 않고 서버에서 데이터를 못가져오는데 postman으로 서버 테스트를 했을때는 잘 되는데요 서버에서 클라이언트로 연동되는 부분에서 문제가 생긴건지 list를 가져오지를 못하고 있습니다 ㅠ 왜 그런건지 알 수 있을까요 ㅠ 오타도 아닌거 같고..
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
이번 final 과제 피드백 부탁드립니다!
안녕하세요! 강의 잘 듣고 있습니다!이번 과제 코드 피드백 부탁드립니다!고맙습니다.<화면><html><!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8"> <title>SignUp</title> <link rel="stylesheet" href="./final.css"> <script defer src="./final.js"></script> </head> <body> <div class="wrapper"> <div class="wrapper__header"> <span id="header__title">코드캠프 회원가입</span> </div> <div class="wrapper__body"> <div class="wrapper__text"> <input type="text" id="email" placeholder="이메일을 입력해 주세요."> <span class="errorMsg email">이메일이 올바르지 않습니다.</span> <input type="text" id="name" placeholder="이름을 입력해 주세요."> <span class="errorMsg name">이름이 올바르지 않습니다.</span> <input type="text" id="pw1" placeholder="비밀번호를 입력해 주세요."> <span class="errorMsg pw1">비밀번호를 입력해주세요.</span> <input type="text" id="pw2" placeholder="비밀번호를 다시 입력해 주세요."> <span class="errorMsg pw2">비밀번호를 입력해주세요.</span> </div> <div class="wrapper__phone" oninput="phone()"> <input type="text" id="num1" maxlength="3"> - <input type="text" id="num2" maxlength="4"> - <input type="text" id="num3" maxlength="4"> </div> <div class="wrapper__certification"> <div class="cert__number"> <span id="certNum">000000</span> <button class="chkBtn" disabled="true">인증번호 전송</button> </div> <div class="cert__time"> <span id="certTimer">3:00</span> <button class="chkBtn" disabled="true">인증완료</button> </div> </div> <div class="wrapper__select"> <div class="select__locale"> <select id="locale"> <option selected disabled>지역을 선택하세요</option> <option value="서울">서울</option> <option value="경기">경기</option> <option value="인천">인천</option> </select> <span class="errorMsg locale">지역을 선택해주세요.</span> </div> <div class="select__gender"> <label for="woman"> <input type="radio" name="gender" id="woman"> 여성 </label> <label for="man"> <input type="radio" name="gender" id="man"> 남성 </label> </div> <span class="errorMsg gender">성별을 선택해주세요.</span> </div> </div> <div class="divideLine"></div> <div class="wrapper__check"> <!-- <button class="submit" disabled="true">가입하기</button> --> <button class="submit">가입하기</button> </div> </div> </body> </html> <css>*{ box-sizing: border-box; margin: 0; } html, body{ width: 540px; } .chkBtn{ width: 120px; height: 40px; border: 1px solid #D2D2D2; border-radius: 7px; font-size: 16px; font-weight: 400; color: #0068FF; background-color: #FFF; cursor: pointer; } .chkBtn.active { width: 120px; height: 40px; border: 1px solid #D2D2D2; border-radius: 7px; font-size: 16px; font-weight: 400; background-color: #0068FF; color: #FFF; cursor: pointer; } .errorMsg{ width: 100%; color: red; font-size: 10px; display: flex; flex-direction: column; align-items: center; visibility: hidden; } .wrapper{ width: 100%; height: 100%; padding: 60px 80px; border: 1px solid #AACDFF; border-radius: 20px; box-shadow: 7px 7px 39px rgba(0, 104, 255, .25); } .wrapper__header{ width: 100%; font-size: 32px; font-weight: 700; color: #0068FF; padding-bottom: 60px; } .wrapper__body{ width: 100%; } .wrapper__text > input{ width: 100%; height: 60px; margin-top: 20px; font-size: 16px; font-weight: 400; border: 1px solid #D2D2D2; border-radius: 7px; padding: 18px; } .wrapper__phone{ width: 100%; display: flex; justify-content: space-between; align-items: center; padding: 20px 0; } .wrapper__phone > input{ width: 100px; height: 40px; border: 1px solid #D2D2D2; border-radius: 7px; } .wrapper__certification { width: 100%; display: flex; flex-direction: column; align-items: flex-end; justify-content: space-between; } #certNum, #certTimer{ color: #0068FF; font-size: 18px; padding-right: 20px; } .cert__time{ padding: 20px 0; } .wrapper__select{ width: 100%; display: flex; flex-direction: column; align-items: center; } .select__locale{ width: 100%; display: flex; flex-direction: column; justify-content: center; } #locale{ width: 100%; height: 60px; border: 1px solid #D2D2D2; border-radius: 7px; color: #797979; font-size: 16px; font-weight: 400; padding: 18px; } .select__gender{ width: 140px; display: flex; justify-content: space-between; padding-top: 30px; } .divideLine{ width: 100%; border: 1px solid #E6E6E6; margin: 20px 0; } .wrapper__check{ width: 100%; display: flex; justify-content: center; } .submit { width: 100%; height: 60px; font-size: 18px; font-weight: 400; color: #0068FF; background-color: #FFF; border: 1px solid #0068FF; border-radius: 7px; } <js>const submit = document.querySelector('.submit'); // 가입하기 const numberChk = document.querySelector('.cert__number .chkBtn'); // 인증번호 전송 const timeChk = document.querySelector('.cert__time .chkBtn'); // 인증완료 let time = 180; // 180초, 인증 시간 let isStarted = false; // email const emailChk = () => { let email = document.getElementById('email').value; if(email.includes('@') === true){ let isEmail = email.split('@')[1].includes('.'); if(isEmail === false){ document.querySelector('.errorMsg.email').style.visibility = 'visible'; document.querySelector('.errorMsg.email').value = ''; return false; } else { document.querySelector('.errorMsg.email').style.visibility = 'hidden'; return true; } } else { document.querySelector('.errorMsg.email').style.visibility = 'visible'; document.getElementById('email').value = ''; return false; } } // name const nameChk = () => { let name = document.getElementById('name').value; if(name.length === 0){ document.querySelector('.errorMsg.name').style.visibility = 'visible'; return false; } else { document.querySelector('.errorMsg.name').style.visibility = 'hidden'; return true; } } // pw const pwChk = () => { let pw1 = document.getElementById('pw1').value; let pw2 = document.getElementById('pw2').value; if(pw1 && pw2){ if(pw1 === pw2){ document.querySelector('.errorMsg.pw1').style.visibility = 'hidden'; document.querySelector('.errorMsg.pw2').style.visibility = 'hidden'; return true; } else { document.querySelector('.errorMsg.pw1').style.visibility = 'visible'; document.querySelector('.errorMsg.pw2').style.visibility = 'visible'; document.querySelector('.errorMsg.pw1').innerHTML = '비밀번호가 일치하지 않습니다.' document.querySelector('.errorMsg.pw2').innerHTML = '비밀번호가 일치하지 않습니다.' return false; } } else { document.querySelector('.errorMsg.pw1').style.visibility = 'visible'; document.querySelector('.errorMsg.pw2').style.visibility = 'visible'; return false; } } // phone const phone = () => { let num1 = document.getElementById('num1').value; let num2 = document.getElementById('num2').value; let num3 = document.getElementById('num3').value; if(num1.length === 3) { document.getElementById('num2').focus(); if(num2.length === 4) { document.getElementById('num3').focus(); } } if(num1.length === 3 && num2.length === 4 && num3.length === 4){ numberChk.classList.add('active'); certification(); } } const certification = () => { // 인증번호 numberChk.disabled = false; numberChk.addEventListener('click', e => { let randomNumber = String(Math.trunc(Math.random() * 1000000)).padStart(6, '0') document.getElementById('certNum').innerText = randomNumber; // 타이머 if(isStarted === false){ isStarted = true; timeChk.disabled = false; let timer = setInterval(() => { if(time >= 0){ let min = Math.trunc(time / 60); let sec = String(time % 60).padStart(2,'0'); document.getElementById('certTimer').innerText = `${min}:${sec}`; time--; } else { clearTime(timer); } }, 100) timeChk.addEventListener('click', e => { if(time >= 0){ alert('인증이 완료 되었습니다.'); clearTime(timer); submit.disabled = false; } }) } }) } const clearTime = (timer) => { timeChk.classList.remove('active'); numberChk.classList.remove('active'); document.getElementById('certNum').innerText = '000000'; document.getElementById('certTimer').innerText = '0:00'; timeChk.disabled = true; numberChk.disabled = true; isStarted = false; clearInterval(timer); } const checkValidation = () => { emailChk(); nameChk(); pwChk(); if(emailChk() && nameChk() && pwChk()) { return true; } else { return false; } } // 검증 submit.addEventListener('click', e => { checkValidation(); if(checkValidation()){ alert('코드캠프 가입을 축하합니다.'); } });
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
함수에 대해 질문있습니다.
자바스크립트 함수가 조금 어려운데 함수는 그냥 관련된 코드들을 작성할 때 사용하나요? 예를 들어 input으로 어떠한걸 한다면 input 함수를 만들어서 이 함수안에는 input과 관련된 코드들을 작성한다고 보면되는건가요?
-
미해결파이썬/장고 웹서비스 개발 완벽 가이드 with 리액트 (장고 4.2 기준)
강의목록 03-05 좋아요 count 멜론 사이트 접근 오류
안녕하세요. 강의 03-05 에서 좋아요 수를 검색하는 Action 에서 오류가 나서 문의 드립니다. 어드민 화면에서 Update Like count 액션을 실행하면 아래 와 같은 에러 페이지가 노출됩니다.강사님 코드를 복사해서 붙여서 해봐도 같은 현상이라서 이것저것 찿아봤지만 도무지 해결이 않되네요. postman에서 도 접근이 않되는데, 브라우저에서 해당 url로 접속하면 데이터가 보이기는 합니다.여기저기 구글링 해보고 이리저리 변경도 해 봤지만.. 해결이 되지않아 질문을 올립니다.제 pc가 회사에 있는 pc라 혹시 로컬 환경이 문제일수 있나 싶기도 하지만, 우선 확인 요청드립니다. 감사합니다.
-
해결됨한 입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지
2.10 Date 객체와 날짜 강의에서 월이 하나씩 추가 됩니다.
안녕하세요. 강의 듣다가 신기해서 질문드려요. 사진에서 보시면 1월로 입력했는데, 콘솔창에는 Feb으로 표시가 됩니다. 다른 달로 바꿔봐도 다음 달이 나오네요.. 그냥 자체 보정해서 (원하는 month - 1) 사용해야하는 건가요??아니면 , , 로 나누는 date는 잘 사용되지 않고, . - / 이 세가지를 사용하면 되는건가요?
-
해결됨한 입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지
리액트 복습하기
안녕하세요. 선생님 강의에 따라서 투두 리스트까지 완강하였는데요. 복습시 이번에 만들어본 프로젝트를 보지 않고 만들 수 있을 때까지 연습해보는 식으로 나아가면 될까요??
-
미해결Next + React Query로 SNS 서비스 만들기
2:56 src/app/page.tsx 파일을 이동 후 not-found 페이지만 뜹니다.
다른분 질문도보고 답변도보고 수정도해보았는데 도저히 안됩니다... 폴더구조입니다. import 오류로 동영상 내용과 동일하게 ../ 를 추가 후 재 호출하면 아래와같이 나옵니다. 소스상 문제는없는것같은데.. 무엇이문제일까요..다른분질문에 AI가 라우팅문제일수있다 했는데 NEXT.CONFIG.JS에 따로 설정도없습니다.다른분질문보니 /app/(beforeLogin)/page.tsx를 넣은것은 /app/page.tsx와 같은거라고 답변이 달린것도봣는데 위 오류에서 벗어날수가없습니다..
-
미해결코드로 배우는 React 19 with 스프링부트 API서버
서비스계층과컨트롤러(3) 상품수정
@PutMapping("/{pno}") public Map<String, String> modify(@PathVariable Long pno, ProductDTO productDTO) { // productDTO안에 pno값만 고정 productDTO.setPno(pno); // 원래 상품을 가지고 온다. old product 가져온다. DB에 저장되어 있는 저장된 정보 ProductDTO oldProductDTO = productService.get(pno); // 새로 업로드할 파일 가져온다. List<MultipartFile> files = productDTO.getFiles(); // 새로 업로드할 파일 저장 List<String> currentUploadFileNames = fileUtil.saveFiles(files); // 지워지지 않는 파일들 keep files 예전 파일 그대로 있는 것 List<String> uploadedFileNames = productDTO.getUploadFileNames(); if(currentUploadFileNames != null && !currentUploadFileNames.isEmpty()) { uploadedFileNames.addAll(currentUploadFileNames); } // 수정하기 productService.modify(productDTO); // 오래된 파일이 문제. 지워져야 하는 파일들 처리 // 기존 파일들을 가져온다. List<String> oldFileNames = oldProductDTO.getUploadFileNames(); if(oldFileNames != null && !oldFileNames.isEmpty()) { // 기존 파일 남아 있는지 확인 // uploadedFileNames에서 없다는건 이 파일은 이제 존재할 의미가 없다는것 그런것만 골라서 모은다. List<String> removeFiles = oldFileNames.stream().filter(fileName -> uploadedFileNames.indexOf(fileName) == -1 ) .collect(Collectors.toList()); // 삭제한다. fileUtil.deleteFiles(removeFiles); } return Map.of("RESULT", "SUCCESS"); }ProductController 에 이 메서드를 입력하고ProductService에는// 수정 void modify(ProductDTO productDTO);이걸 입력하고ProductServiceImpl에는@Override public void modify(ProductDTO productDTO) { // 조회 Optional<Product> result = productRepository.findById(productDTO.getPno()); Product product = result.orElseThrow(); // 변경내용 반영 product.changePrice(productDTO.getPrice()); product.changeName(productDTO.getPname()); product.changeDesc(productDTO.getPdesc()); product.changeDel(productDTO.isDelFlag()); // 이미지 처리를 위해 목록을 비운다. List<String> uploadFileNames = productDTO.getUploadFileNames(); product.clearList(); if(uploadFileNames != null && uploadFileNames.isEmpty()) { uploadFileNames.forEach(uploadName ->{ product.addImageString(uploadName); }); } // 저장될 때 파일이 문제 파일이 변경됐는지 알 수 가 없다. productRepository.save(product); } private ProductDTO entityToDTO(Product product) { ProductDTO productDTO = ProductDTO.builder() .pno(product.getPno()) .pname(product.getPname()) .pdesc(product.getPdesc()) .price(product.getPrice()) .delFlag(product.isDelFlag()) .build(); List<ProductImage> imageList = product.getImageList(); if(imageList == null || imageList.isEmpty()) { return productDTO; } // 상품 이미지 목록 문자열로 바꾸기 List<String> fileNameList = imageList.stream().map(productImage -> productImage.getFileName()).toList(); productDTO.setUploadFileNames(fileNameList); return productDTO; } 이걸 입력하고 postman에서 PUT방식으로 해서 기존 이미지파일 내용을 그대로 복사해서 테스트를 하는데 "msg": "Validation failed for argument [1] in public java.util.Map<java.lang.String, java.lang.String> org.zerock.apiserver.controller.ProductController.modify(java.lang.Long,org.zerock.apiserver.dto.ProductDTO): [Field error in object 'productDTO' on field 'uploadFileNames': rejected value [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@192a0968]; codes [typeMismatch.productDTO.uploadFileNames,typeMismatch.uploadFileNames,typeMismatch.java.util.List,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [productDTO.uploadFileNames,uploadFileNames]; arguments []; default message [uploadFileNames]]; default message [Failed to convert property value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'java.util.List' for property 'uploadFileNames'; Cannot convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'java.lang.String' for property 'uploadFileNames[0]': no matching editors or conversion strategy found]] "이런 에러가 계속 발생하는데요 왜 그럴까요 ㅠpostman에서 출력하는 메세지입니다. GTP에 입력해서 물어봤는데ProductController의 modify 메서드에서 ProductDTO 객체의 uploadFileNames 필드가 잘못된 타입으로 전달되었기 때문에 발생합니다. 이런 메세지를 주는데 강의 내용과 똑같이 입력했는데 왜 이런 메세지를 뱉어내는지 잘 모르겠습니다 ㅠ
-
미해결파이썬/장고 웹서비스 개발 완벽 가이드 with 리액트 (장고 4.2 기준)
섹션 11 체크리스트 링크 확인 요청
안녕하세요.알차게 준비해주신 강의 잘 듣고 있습니다.강의 수강 중 섹션 11에서 참고하고 있는 체크리스트 링크가 수업노트에 기재되어 있지 않아 문의 드립니다.
-
미해결iOS/Android 앱 개발을 위한 실전 React Native - Basic
강의 자료 소스코드는 없나요?
제목 그대로 강의 자료로 완성된 소스코드는 따로 없는지 문의 드립니다 다른 강의들은 다 주던대
-
미해결[React 1부] 만들고 비교하며 학습하는 React
import 문제
안녕하세요. 먼저 수업 잘 듣고 있습니다 🙂 6:41 부분에서 import 문제가 발생하는데 main.js 기준으로 helpers.js는 동일한 경로에 있으므로 ./helpers.js가 맞지 않나요? IDE에서 자동완성으로 작성해도 이 경로로 작성됩니다. 오히려 /js/helpers.js로 기입하면 cannot resolve file이라고 경고 뜨더라구요. 근데 또 강의처럼 /js 경로를 안넣으면 에러가 발생하네요... 제가 아직 지식이 얕아 혹시나 질문드려봅니다. ㅠ
-
미해결Next + React Query로 SNS 서비스 만들기
default.tsx를 넣는대신 modal의 타입을 ?로 하면안되나요?
modal이 없는 상황의 오류를 해결하기위해 제로초님이 default.tsx라는 파일을 소개해줬는데요, 그냥 layout.tsx에서 애초에 Probs를 정의할때 type Probs= modal?:reactNode로 하면 안될까요?
-
해결됨한 입 크기로 잘라먹는 타입스크립트(TypeScript)
npx create-reacp-app src폴더 누락
npx create-react-app을 통하여 react를 설치하려 했는데 node_modules와 pakage.json만 생성되고 public 폴더와 src 폴더는 생성이 되지 않습니다. 이미지에 나온 문구대로 입력도 해보고 nodejs를 완전히 삭제 후 재 설치도 해보았지만 폴더 누락이 계속 일어나고 있습니다. 왜 이런 현상이 나타나는 건가요?
-
해결됨처음 만난 리액트(React)
LifeCycle 문의
안녕하세요 강의 감사히 잘 듣고 있습니다.다름이 아니라 chapter06에서 코드는 같은데Notification의 componentDidUpdate() 한번씩 더 호출되는데 이유를 모르겠습니다.import React from "react"; const styles = { wrapper: { margin: 8, padding: 8, display: "flex", flexDirection: "row", border: "1px solid grey", borderRadius: 16, }, messageText: { color: "black", fontSize: 16, }, }; class Notification extends React.Component { constructor(props) { super(props); this.state = {}; } componentDidMount() { console.log(`${this.props.id} componentDidMount() called.`); } componentDidUpdate() { console.log(`${this.props.id} componentDidUpdate() called.`); } componentWillUnmount() { console.log(`${this.props.id} componentWillUnmount() called.`); } render() { return ( <div style={styles.wrapper}> <span style={styles.messageText}>{this.props.message}</span> </div> ); } } export default Notification;import React from "react"; import Notification from "./Notification"; const reservedNotifications = [ { id: 1, message: "안녕하세요, 오늘 일정을 알려드립니다.", }, { id: 2, message: "점심식사 시간입니다.", }, { id: 3, message: "이제 곧 미팅이 시작됩니다.", }, ]; var timer; class NotificationList extends React.Component { constructor(props) { super(props); this.state = { notifications: [], }; } componentDidMount() { const { notifications } = this.state; timer = setInterval(() => { if (notifications.length < reservedNotifications.length) { const index = notifications.length; notifications.push(reservedNotifications[index]); this.setState({ notifications: notifications, }); } else { this.setState({ notifications: [], }); clearInterval(timer); } }, 1000); } componentDidUpdate() { console.log(` parent componentDidUpdate() called.`); } componentWillUnmount() { if (timer) { clearInterval(timer); } } render() { return ( <div> {this.state.notifications.map((notification) => { return ( <Notification key={notification.id} id={notification.id} message={notification.message} /> ); })} </div> ); } } export default NotificationList;추가로 NotificationList의 componentDidUpdate()가 계속 호출되는데 이유가 있을까요?
-
미해결Next + React Query로 SNS 서비스 만들기
msw patch
안녕하세요 msw patch 관련해서 여쭤보고싶은게 있습니다!제로초님 강의를 응용해서 프로젝트에 msw로 데이터들을 테스트 하고있습니다 handler에서 /users란 엔드포인트로 get요청후 데이터들을 받아온뒤 다시 수정이 필요해 patch handler를 생성했습니다. mutation을 통해서 patch 요청은 성공한거같은데 기존의 get으로 받아온 user데이터들을 수정하고 싶다면 어떻게 할수있을지 여쭤보고싶습니다 ! const mutation = useMutation({ mutationFn: async (e: FormEvent) => { e.preventDefault(); const updatedUser = { userId: product.userId, nickName: product.nickName, userFileUrl: product.userFileUrl, techStack: product.techStack, position: product.position, employmentStatus: product.employmentStatus, year: product.year, links: product.links, alarmStatus: product.alarmStatus, content: product.content, softSkill: product.softSkill, }; fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/users`, { method: "PATCH", body: JSON.stringify(updatedUser), }); }, }); import { bypass, http, HttpResponse } from "msw"; import { hotPeople, peoples, users } from "./peopleData"; export const handlers = [ http.get("/peoples/hot/:tag", () => { return HttpResponse.json(hotPeople); }), http.get("/peoples", ({ request, params }) => { return HttpResponse.json(peoples); }), http.get("/users", () => { return HttpResponse.json(users); }), http.patch("/users", async ({ request }) => { return HttpResponse.text("success?"); }), ]; export default handlers;
-
미해결처음 만난 리액트(React)
item의 값을 어디서 얻어오는지 모르겠습니다..
안녕하세요 onClickItem에서 (item) 이 데이터를 어디서 가져오는지 이해가 가지 않아서요,,item이라고 명시된 값이 없는데 item을 어떻게 사용하는 건가요..???
-
미해결따라하며 배우는 리액트 A-Z[19버전 반영]
CSS
영화 상세페이지 구현에서 className으로 modal_poster-img를 주니까 다른 곳에 있던 css가 적용되는데 위에 import하지 않아도 가능한건가요??