묻고 답해요
150만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
순위 정보를
불러오고 있어요
-
미해결한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지
SSR, CSR 관련 질문입니다.
현직 개발자입니다. 생각이 많아져서 질문드립니다.SSR(타임리프, JSP), CSR(Vue3) 을 프로젝트 경험하면서.. 이런저런 생각이 드는데요.1.CSR은 SEO문제 해결이 가능한가요?2.CSR은 컴포넌트 재사용이 장점이나 화면복잡도가 높아질 경우 코드 복잡도가 높아진다고 생각되는데 어떻게 생각하시는지요?3.SSR이 화면 깜빡임이 있다고 하는데, 실은 비동기 통신하면 화면 깜빡임은 제어 가능합니다. html자체를 바꿔서 렌더링 하는게 아닌 화면 하나당 html하나로 렌더링하는거죠.(메뉴이동시에만 html이동하니 메뉴이동시 초기화면은 깜빡임은 있음)강의 내용에 있는 Tab은 한화면에 구성하면 깜빡일 일도 없고, 내부 공통 기능들은 공통JS로 빼고 틀은 같이 쓰고, 공통부분은 템플릿관련 JS로 처리하면 크게 다른부분을 모르겠습니다.화면 내에서는 전부 비동기 통신 Ajax로 처리하면 깜빡임은 없더라구요.4.CSR은 SPA기반이라 초기화면이 모바일쪽이 더 심플해서 나을거 같다라는 생각이 듭니다.대형 포털을 CSR기반으로 하면 복잡도도 높아지고, 제 경험엔 초기화면 또는 복잡한 화면들이 많이 느려지더라구요. 어떻게 생각하시는지요?SSR, CSR이 어떤 상황에 적용되는게 나을지에 대한 의문이 항상 있습니다.그냥 강의듣다가 개인적인 질문 드려봅니다.cf. 강의 내용은 아주 잘 듣고 있습니다.^^
-
해결됨한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지
TabBar.js 오류가 자꾸 발생하는데 무슨이유인지 모르겠습니다;;
전체 사진 처음 화면은 로딩 되서 잘나오는데 펭귄이나 다른탭을 클릭하면 아래와 같은 오류가 나오는데 TabBar.js onclick 함수가 아니라는데;; 왜이런건지 함수가 맞는데 아래에 제가 작성한 코드 입니다 검토 좀 부탁드립니다.^^;;TabBar.jsexport default function TabBar({ $app, initialState, onClick }) { // TabBar 클래스를 생성합니다. 초기값과 클릭 이벤트를 받습니다. this.state = initialState; // 초기값 설정 this.onClick = onClick; // 클릭 이벤트 설정 this.$target = document.createElement("div"); // 새로운 div 요소를 생성합니다. this.$target.className = "tab-bar"; // div 요소에 클래스 이름을 추가합니다. $app.appendChild(this.$target); // $app 요소에 div 요소를 추가합니다. this.template = () => { let temp = `<div id="all">전체</div><div id="penguin">펭귄</div> <div id ="koala">코알라</div><div id ="panda">판다</div>`; // 전체 탭을 추가합니다. return temp; // temp를 반환합니다. }; this.render = () => { // 렌더링 함수 this.$target.innerHTML = this.template(); // div 요소의 innerHTML을 template 함수의 반환값으로 설정합니다. let $currentTab = document.getElementById(this.state); // 현재 탭을 선택합니다. // $currentTab ? ($currentTab.className = "clicked") : ""; // 현재 탭이 존재하면 clicked 클래스를 추가합니다. 없으면 변화없음. $currentTab && ($currentTab.className = "clicked"); // && 연산자를 사용하여 현재 탭이 존재하면 clicked 클래스를 추가합니다. const $tabBar = this.$target.querySelectorAll("div"); // 모든 div 요소를 tabBar 요소에 담아온다. $tabBar.forEach((elm) => { elm.addEventListener("click", () => { // 각 div 요소에 클릭 이벤트 리스너를 추가합니다. this.onClick(elm.id); // 클릭한 div 요소의 id를 onClick 함수에 전달합니다. }); }); }; this.setState = (newState) => { // state를 변경하는 함수 this.state = newState; // state를 새로 받은 newState로 업데이트합니다. this.render(); // state가 변경되면 렌더링 함수를 다시 호출하여 화면을 업데이트합니다. }; this.render(); // 렌더링 함수를 호출합니다. } App.jsimport TabBar from "./components/TabBar.js"; // TabBar.js 파일을 불러옵니다. import Content from "./components/Content.js"; // Content.js 파일을 불러옵니다. import { request } from "./components/api.js"; // api.js 파일을 불러옵니다. export default function App($app) { // App 생성자 함수를 생성합니다. // $app은 App 컴포넌트가 렌더링될 DOM 요소입니다. this.state = { //state 초기값 설정 currentTab: "all", // 탭 초기값 설정 tabbar 컴포넌트에 전달할 현재 탭 데이터 photos: [], // 사진 초기값 설정 content 컴포넌트에 전달할 사진 데이터 }; const tabbar = new TabBar({ $app, // App 컴포넌트가 렌더링될 DOM 요소를 전달합니다. initialState: "", // 초기값 설정 oncClick: async (name) => { // 클릭 이벤트 설정 변경값을 currentTab에 저장 this.setState({ // 클릭한 탭의 데이터를 state에 저장합니다. ...this.State, // 기존 state를 복사합니다. 스프레드 연산자 currentTab: name, // 클릭한 탭의 이름을 currentTab에 저장합니다. photos: await request(name === "all" ? "" : name), // 클릭한 탭의 새로운 사진을 request 이름으로 함수를 불러와 저장합니다. // request 함수는 비동기 함수로 async await를 사용하여 데이터를 받아옵니다. }); }, }); const content = new Content({ $app, // App 컴포넌트가 렌더링될 DOM 요소를 전달합니다. initialState: [], // 초기값 설정 }); this.setState = (newState) => { // 업데이트 값을 newState로 받습니다. this.state = newState; // state를 새로 받은 newState로 업데이트합니다. tabbar.setState(this.state.currentTab); // tabbar 컴포넌트에 state를 전달합니다. content.setState(this.state.photos); // content 컴포넌트에 state를 전달합니다. }; const init = async () => { //웹페이지가 로드되면 실행되는 함수 try { const initialPhotos = await request(); // request 함수를 불러와 initialPhotos에 저장합니다. this.setState({ // state를 initialPhotos로 업데이트합니다. ...this.state, // 기존 state를 복사합니다. 스프레드 연산자 photos: initialPhotos, // initialPhotos를 photos에 저장합니다. }); } catch (err) { console.log(err); } }; init(); // 웹애플리케이션이 실행될때 init 함수를 실행합니다. } index.jsimport App from "../src/App.js"; const $app = document.getElementById("app"); new App($app); api.jsconst API_URL = "https://animal-api-two.vercel.app"; // 이미지 url을 변수에 저장 // const $content = document.querySelector("div.content"); //(api 불러오는 코드만 남겨놓기 위해 삭제제) // let template = []; // (api 불러오는 코드만 남겨놓기 위해 삭제제) //API export const request = async (name) => { const res = await fetch(name ? `${API_URL}/${name}` : API_URL); // fetch 함수를 사용하여 API_URL을 호출합니다. name이 있으면 name을 호출합니다. 없으면 API_URL을 호출합니다. try { if (res) { let data = await res.json(); return data.photos; } } catch (err) { console.log(err); } }; index.html<!DOCTYPE html> <head> <title>Animal Album</title> <meta charset="UTF-8" /> <link rel="stylesheet" href="../project2/src/style.css" /> <script type="module" src="../project2/src/index.js" defer></script> </head> <body> <div id="app"> <!-- TAB BAR --> <!-- CONTENT --> </div> </body> content.jsexport default function Content({ $app, initialState }) { this.state = initialState; this.$target = document.createElement("div"); this.$target.className = "Content"; $app.appendChild(this.$target); this.template = () => { let temp = []; if (this.state) { this.state.forEach((elm) => { temp += `<img src="${elm.url}"></img>`; }); } return temp; }; this.render = () => { this.$target.innerHTML = this.template(); }; this.setState = (newState) => { this.state = newState; this.render(); }; this.render(); } 콘솔 오류코드 TabBar.js:26 Uncaught TypeError: this.onClick is not a function at HTMLDivElement.<anonymous> (TabBar.js:26:14)
-
해결됨한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지
Header에서 정렬기준
Header에서 total, cost, fun 등 정렬 값이 바뀌는 건 알겠는데, 이 값이 바뀔 때 점수가 높은순으로 정렬이 되는데, 이 정렬을 지정해주는 실행 코드가 어디에 있는지 모르겠어요. <div class="filter"> <select id="sortList" class="sort-list"> <option value="total" ${sortBy === 'total' ? 'selected' : ''}>Total</option> <option value="cost" ${sortBy === 'cost' ? 'selected' : ''}>Cost</option> <option value="fun" ${sortBy === 'fun' ? 'selected' : ''}>Fun</option> <option value="safety" ${sortBy === 'safety' ? 'selected' : ''}>Safety</option> <option value="internet" ${sortBy === 'internet' ? 'selected' : ''}>Internet</option> <option value="air" ${sortBy === 'air' ? 'selected' : ''}>Air Quality</option> <option value="food" ${sortBy === 'food' ? 'selected' : ''}>Food</option> </select> </div>
-
해결됨한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지
2-3 동물 사진 request 오류
안녕하세요 코드 궁금증은 아니구요 이렇게 request로 이미지 불러오기를 했을 때 이미지를 불러오긴 하는거 같은데GET http://127.0.0.1:5500/undefined 404 (Not Found)와 같은 오류가 발생하면서 엑박이 뜨거든요... 도저히 제가 어디서 잘못했는지 발견을 못하겠어서 혹시 해결 방법을 아신다면 알려주시면 감사드리겠습니다...
-
해결됨한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지
병령처리 하지만 동기화와 같은 출력값
const workA = () => { return new Promise((resolve) => { setTimeout(() => { resolve(`workA`); }, 5000); }); }; const workB = () => { return new Promise((resolve) => { setTimeout(() => { resolve(`workB`); }, 3000); }); }; const workC = () => { return new Promise((resolve) => { setTimeout(() => { resolve(`workC`); }, 10000); }); }; const start = async () => { try { let results = await Promise.all([workA(), workB(), workC()]); console.log(results); results.forEach((res) => console.log(res)); } catch (err) { console.log(err); } };[10:01] 강의 내용 보면 workA가 5초 workB가 3초, workC가 10초인데, 결국 출력 되는 값을 보면 동시에 출력이 됩니다.그리고 순서도 A, B, C 순입니다.let resultA = await workA(); let resultB = await workB(); let resultC = await workC(); console.log(resultA); console.log(resultB); console.log(resultC);물론 실행시간의 차이는 있지만, 실직적으로 프로그램에 표기 되는 값은 바로 위에 있는 코드예제에서 보여주신 A, B, C랑 같은데, 병령처리라면 시간이 짧은 B가 실행되고 그 다음에 A, 그 다음 C가 아웃풋으로 나와야 하는거 아닌가요??
-
해결됨한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지
API 관련 질문
안녕하세요 !해당 강의를 듣고 기능은 비슷한데 내용은 조금 다른 홈페이지를 제작해보고 싶어져서 질문 드립니다 !API를 호출하는 기능은 이해했는데, 강사님이 만드신 API 처럼 저도 직접 간단한 정보를 담은 api 를 만들어보고 싶은데 이 부분은 어떻게 제작하는 지 알 수 있을까요?!
-
해결됨한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지
citiList 의 더보기 버튼 함수
안녕하세요 citiList 에 더보기 버튼이 있는데handleLoadMore 함수가 더보기 버튼을 클릭했을 때 동작하는 함수인 것 이해했습니다. 근데 해당함수는 citiList 컴포넌트에서만 사용하니까 CitiList.js 에 작성할것으로 예상했는데App.js 에 작성하셔서 App.js 에서 작성하고 CitiList 로 전달하는 이유가 궁금합니다!
-
해결됨한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지
input 태그 value문제 해결 방법
초기값이 '' 이여서강의에서는 value 값을 맨뒤로 넣고 input 태그에 닫힘을 작성하지 않음으로, 동작하게 하였는데 다른 방법으로는 <input type="text" placeholder="Search" id="search" value="${searchWord}" autocomplete="off"/>로 작성하였습니다, value 를 싱글쿼터나 더블쿼터로 감싼다음 ${} 를 사용하시면, 뒤에다가 다른 속성을 넣거나 닫아도 정상 동작합니다. 참고 하실분 참고하셔도 좋습니다.
-
해결됨한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지
9분 30초 || 'all' 영상 누락
혹시나 기본 '/' 경로에서 펭귄눌렀다 popstate 로 뒤로갔을 경우'clicked' css가 먹지않는 현상, 강의 내용에서 저부분이 영상 짤려서 놓치기 쉬울꺼 같습니다. 저도 강의보면서 하다가 || 'all' 하는 부분 제대로 보기힘들어서못 적었다가 나중에 문제생겨서 로직 보다가 발견했습니다,
-
해결됨한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지
영상보고 직접 api를 구현해봤는데 자꾸 프로젝트를 변경하면 서버가 꺼지;는데 방법이 있을까요
코드 관련 질문은 아래와 같이 '코드블럭' 기능을 이용해주세요!+ 오류 메세지도 함께 올려주시면 좋아요 🙂console.log('hello'); 이런식으로 구축했는데 프로젝트만 바꾸면 서버가 꺼져서요..
-
미해결React + API Server 프로젝트 개발과 배포 (CI/CD)
nginx 에러 질문
안녕하세요. 도메인등록과 HTTPS설정을 끝까지 따라했는데 certbot --nginx 이후 접속해봤을 때 아래 [그림 1]과 같이 나타나고 접속이 불가능합니다.[그림 2]와 같이 nginx.conf에는 certbot 관련 설정이 추가는 된 것 같습니다. 다만, 따라하는 과정 중 제게는 [그림 3] 같은 선택지 질문이 있엇습니다. 어떻게 조치를 하면 좋을까요..? [그림 1] [그림 2] [그림 3]
-
해결됨React + API Server 프로젝트 개발과 배포 (CI/CD)
https 인증서 설정과정 설치 문제 질문
안녕하세요. https 인증서 설정 과정을 따라하고 있는데 아래 설치 명령을 따라하는 과정에서 설치가 안되는 문제가 있습니다. yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm 위 설치 명령어를 실행하면 아래와 같이 터미널에 나타납니다.윈도우 git bash로 접속해도 동일합니다. 왜 cannot open이라고 나타날까요.. 어떻게 해결해야할가요..? [내용 추가]위 yum install 뒤에 url을 따라가니 현재 해당 경로에 epel-release-latest-7.noarch.rpm이 없는 것 같습니다.
-
해결됨React + API Server 프로젝트 개발과 배포 (CI/CD)
AWS EC2와 로컬 PC에서의 차이가 이해가 안되고 nginx의 필요성이 궁금합니다.
Q1. EC2와 로컬 PC의 차이강의를 따라하며 nginx를 셋팅하고 AWS에서 pm2로 실행시켰을 땐,AWS EC2 머신의 주소만으로 포트 없이도 타고들어가면 바로 웹브라우저에서 react SPA가 실행되었습니다. (강의대로 잘 따라감, 비용 때문에 https, 도메인등록 강의 시청만하고 따라하진 않았습니다..) 이해가 안되는 점은 동일한 프로젝트인데 로컬 PC에서 react를 build하고 동일하게 backend/public 폴더 아래 복사하였는데 localhost:4000으로 접속하면 Express, Welcome to Express 페이지가 뜹니다. 물론 로컬 PC에서는 niginx를 셋팅하지 않았다라는 점이 다른점이긴한데 nginx를 설정할 때 이해되기로 접속시 EC2 머신의 localhost:4000으로 연결하는 것 뿐이고EC2 머신 & 로컬 PC 모두 backend express.js 프로젝트 상에서 "/*"으로의 라우팅을 raact build 내 index.html로 연결하는 코드는 동일하게 없다라는 점에서왜 EC2만 react SPA가 실행되는건지 모르겠습니다. Q2. nginx의 필요성pm2로 실행한다고 하면 이미 프로세스를 충분히 관리한다고 생각이 드는데.. nginx의 필요성 궁금합니다.
-
해결됨한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지
경로 질문드립니다
코드 관련 질문은 아래와 같이 '코드블럭' 기능을 이용해주세요!+ 오류 메세지도 함께 올려주시면 좋아요 🙂npm error code ENOENT npm error syscall open npm error path C:\Users\사용자이름\Desktop\animal_album_Main\animal_album-3\package.json npm error errno -4058 npm error enoent ENOENT: no such file or directory, open 'C:\Users\사용자이름\Desktop\animal_album_Main\animal_album-3\package.json' npm error enoent This is related to npm not being able to find a file. npm error enoent npm error A complete log of this run can be found in: C:\Users\사용자이름\AppData\Local\npm-cache\_logs\2024-12-06T08_26_22_967Z-debug-0.log 안녕하세요 질문드립니다몇일동안 npm init 떄문에 질문드립니다 npm 설치시 해당 프로젝트 파일이 c드라이브 안에만 있어야 되는건가요 ?1번 바탕화면에 프로젝트가 있을떄도 실행이 안됩니다2번 c드라이브 -> User -> (사용자이름) -> github-> 해당 폴더 -> 프로젝트 폴더3번 c드라이브 -> 프로젝트 폴더 3번일때만 되고 1,2번일때는 npm init 설치가 안되는데2번도 가능하게 할려면 어떻게 해야하는지 궁금합니다
-
해결됨한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지
regionList 에 region별 cities가 정상 로딩이 안됩니다.
영상 7:53 부분에 코드를 완성하면, regionList에 있는 region 클릭 시, 영상처럼 region 별로 cities가 나와야 하지만, 아래 에러가 생겨서 정상적으로 로딩이 안됩니다.혹시 어떤 문제 인지 알려주시면, 너무 고맙습니다. 감사합니다! app.js 코드는 아래와 같이 입력했습니다.import Header from "./components/Header.js"; import RegionList from "./components/RegionList.js"; import CityList from "./components/CityList.js"; import CityDetail from "./components/CityDetail.js"; import { request } from "./components/api.js"; export default function App($app) { const getSortBy = () => { if (window.location.search) { return window.location.search.split("sort=")[1].split("&")[0]; } return "total"; }; const getSearchWord = () => { if (window.location.search && window.location.search.includes("search=")) { return window.location.search.split("search=")[1]; } return ""; }; this.state = { startIdx: 0, sortBy: getSortBy(), searchWord: getSearchWord(), region: "", cities: "", }; const header = new Header({ $app, initialState: { sortBy: this.state.sortBy, searchWord: this.state.searchWord, }, handleSortChange: async (sortBy) => { const pageUrl = `/${this.state.region}?sort=${sortBy}`; history.pushState( null, null, this.state.searchWord ? pageUrl + `&search=${this.state.searchWord}` : pageUrl ); const cities = await request( 0, this.state.region, sortBy, this.state.searchWord ); this.setState({ ...this.state, startIdx: 0, sortBy: sortBy, cities: cities, }); }, handleSearch: async (searchWord) => { history.pushState( null, null, `/${this.state.region}?sort=${this.state.sortBy}&search=${searchWord}` ); const cities = await request( 0, this.state.region, this.state.sortBy, searchWord ); this.setState({ ...this.state, startIdx: 0, searchWord: searchWord, cities: cities, }); }, }); const regionList = new RegionList({ $app, initialState: this.state.region, handleRegion: async (region) => { history.pushState(null, null, `/${region}?sort=total`); const cities = await request(0, region, "total"); this.setState({ ...this.state, startIdx: 0, sortBy: "total", region: region, searchWord: "", cities: cities, }); }, }); const cityList = new CityList({ $app, initialState: this.state.cities, handleLoadMore: async () => { const newStartIdx = this.state.startIdx + 40; const newCities = await request( newStartIdx, this.state.region, this.state.sortBy, this.state.searchWord ); this.setState({ ...this.state, startIdx: newStartIdx, cities: { cities: [...this.state.cities.cities, ...newCities.cities], isEnd: newCities.isEnd, }, }); }, }); const cityDetail = new CityDetail(); this.setState = (newState) => { this.state = newState; cityList.setState(this.state.cities); header.setState({ sortBy: this.state.sortBy, searchWord: this.state.searchWord, }); regionList.setState(this.state.region); }; const init = async () => { const cities = await request( this.state.startIdx, this.state.region, this.state.sortBy, this.state.searchWord ); console.log(cities); this.setState({ ...this.state, cities: cities, }); }; init(); } regionList.js 코드는 아래와 같이 입력했습니다.export default function RegionList({ $app, initialState, handleRegion }) { this.state = initialState; this.$target = document.createElement("div"); this.$target.className = "region-list"; this.handleRegion = handleRegion; $app.appendChild(this.$target); this.template = () => { const regionList = [ "🚀 All", "🌏 Asia", "🕌 Middle-East", "🇪🇺 Europe", "💃 Latin-America", "🐘 Africa", "🏈 North-America", "🏄 Oceania", ]; let temp = ``; regionList.forEach((elm) => { let regionId = elm.split(" ")[1]; temp += `<div id=${regionId}>${elm}</div>`; }); return temp; }; this.render = () => { this.$target.innerHTML = this.template(); if (this.state) { let $currentRegion = document.getElementById(this.state); $currentRegion && ($currentRegion.className = "clicked"); } else { document.getElementById("All").className = "clicked"; } const $regionList = this.$target.querySelectorAll("div"); $regionList.forEach((elm) => { elm.addEventListener("click", () => { this.handleRegion(elm.id); }); }); }; this.setState = (newState) => { this.state = newState; this.render(); }; this.render(); }
-
해결됨한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지
regionList 클릭시 해당 cities가 안나옵니다.
혼자서 찾아보려고 했는데 도저히 모르겠네요 ㅜ 오류메세지는 나오는건 없고 제목과 같습니다. region을 선택하면 해당 cities가 나와야하는데 안나와요 ㅜ import Header from "./components/Header.js"; import RegionList from "./components/RegionList.js"; import CityDetail from "./components/CityDetail.js"; import CityList from "./components/CityList.js"; import { request } from "./components/api.js"; export default function App($app){ const getSortBy = () => { if (window.location.search){ return window.location.search.split('sort=')[1].split('&')[0]; } return 'total'; }; const getsearchWord = () => { if(window.location.search && window.location.search.includes('search=')){ return window.location.search.split('search=')[1] } //뒤에 있는 값을 반환 return ''; }; this.state={ startIdx : 0, sortBy : getSortBy(), region: '', searchWord: getsearchWord(), cities:'', }; const header = new Header({ $app, initialState:{ sortBy:this.state.sortBy, searchWord:this.state.searchWord }, handleSortChange: async(sortBy) => { const pageUrl = `/${this.state.region}?sort=${sortBy}`; history.pushState( null, null, this.state.searchWord ? pageUrl + `&search=${this.state.searchWord}` : pageUrl ); //변경된 정렬기준을 적용한 새로운 데이터를 불러옴 (매개변수로 전달받은 새로운 정렬기준인 sortBy 값을 넣어야함) const cities = await request(0, this.state.region, sortBy, this.state.searchWord); // 변경된 상태값을 업데이트 this.setState({ ...this.state, startIdx:0, sortBy: sortBy, cities: cities, }); }, handleSearch: async(searchWord) => { //웹사이트 주소를 알맞게 변경 history.pushState( null, null, `/${this.state.region}?sort=${this.state.sortBy}&search=${searchWord}` ); const cities = await request(0, this.state.region, this.state.sortBy, searchWord); this.setState({ ...this.state, startIdx:0, searchWord: searchWord, cities: cities }) }, }); const regionList = new RegionList({ $app, initialState:this.state.region, handleRegion: async(region) => { history.pushState(null, null, `/${region}?sort=total`); const cities = await request(0, region, 'total'); console.log("cities",cities) this.setState({ ...this.state, startIdx: 0, region: region, sortBy: 'total', cities: cities, searchWord: '', }); }, }); const cityList = new CityList({ $app, initialState:this.state.cities, // 아래는 더보기 버튼을 눌렀을 때 실행되는 것 handleLoadMore: async() => { const newStartIdx = this.state.startIdx + 40; const newCities = await request(newStartIdx, this.state.region, this.state.sortBy, this.state.searchWord); this.setState({ ...this.state, startIdx : newStartIdx, cities:{ cities:[...this.state.cities.cities, ...newCities.cities], isEnd: newCities.isEnd, } }) } }); const cityDetail = new CityDetail(); this.setState = (newState) => { this.state = newState; cityList.setState(this.state.cities); header.setState({sortBy:this.state.sortBy, searchWord:this.state.searchWord}); regionList.setState(this.state.region); }; const init = async() => { const cities = await request(this.state.startIdx, this.state.sortBy, this.state.region, this.state.searchWord); this.setState({ ...this.state, cities: cities, //api 호출의 결과인 cities }); }; init(); } export default function RegionList({$app, initialState, handleRegion}){ this.state = initialState; this.$target = document.createElement('div'); this.$target.className = 'region-list'; this.handleRegion = handleRegion; $app.appendChild(this.$target); this.template = () => { const regionList = [ '🚀 All', '🌏 Asia', '🕌 Middle-East', '🇪🇺 Europe', '💃 Latin-America', '🐘 Africa', '🏈 North-America', '🏄 Oceania', ]; let temp = ``; regionList.forEach((elm) => { let regionId = elm.split(' ')[1]; temp += `<div id=${regionId}>${elm}</div>`; }); return temp; }; this.render = () => { this.$target.innerHTML = this.template(); let $currentRegion; if(this.state){ $currentRegion = document.getElementById(this.state); $currentRegion && ($currentRegion.className = 'clicked'); } else { document.getElementById('All').className = 'clicked'; } const $regionList = this.$target.querySelectorAll('div'); $regionList.forEach((elm) => { elm.addEventListener('click', () => { this.handleRegion(elm.id); }); }); }; this.setState = (newState) => { this.state = newState; this.render(); }; this.render(); }
-
해결됨한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지
select값이 출력이 안돼요
input 값은 나오는데 select 값은 출력이 안돼요 ㅠ 오류 메세지도 따로 나오는 건 없고 console.log로 cities 값을 볼려고 했는데 빈 Array가 나옵니다 ㅠ import Header from "./components/Header.js"; import RegionList from "./components/RegionList.js"; import CityDetail from "./components/CityDetail.js"; import CityList from "./components/CityList.js"; import { request } from "./components/api.js"; export default function App($app){ const getSortBy = () => { if (window.location.search){ return window.location.search.split('sort=')[1].split('&')[0]; } return 'total'; }; const getSearchWorld = () => { if(window.location.search && window.location.search.includes('search=')){ return window.location.search.split('search=')[1] } //뒤에 있는 값을 반환 return ''; }; this.state={ startIdx : 0, sortBy : getSortBy(), searchWorld: getSearchWorld(), region: '', cities:'', }; const header = new Header({ $app, initialState:{ sortBy:this.state.sortBy, searchWorld:this.state.searchWorld }, handleSortChange: async(sortBy) => { const pageUrl = `/${this.state.region}?sort=${sortBy}`; history.pushState( null, null, this.state.searchWorld ? pageUrl + `&search=${this.state.searchWorld}` : pageUrl ); //변경된 정렬기준을 적용한 새로운 데이터를 불러옴 (매개변수로 전달받은 새로운 정렬기준인 sortBy 값을 넣어야함) const cities = await request(0, this.state.region, sortBy, this.state.searchWorld); console.log(cities) // 변경된 상태값을 업데이트 this.setState({ ...this.state, startIdx:0, sortBy: sortBy, cities: cities, }); }, handleSearch: async(searchWorld) => { //웹사이트 주소를 알맞게 변경 history.pushState( null, null, `/${this.state.region}?sort=${this.state.sortBy}&search=${searchWorld}` ); const cities = await request(0, this.state.region, this.state.sortBy, searchWorld); this.setState({ ...this.state, startIdx:0, searchWorld: searchWorld, cities: cities }) }, }); const regionList = new RegionList(); const cityList = new CityList({ $app, initialState:this.state.cities, // 아래는 더보기 버튼을 눌렀을 때 실행되는 것 handleLoadMore: async() => { const newStartIdx = this.state.startIdx + 40; const newCities = await request(newStartIdx, this.state.sortBy, this.state.region, this.state.searchWorld); this.setState({ ...this.state, startIdx : newStartIdx, cities:{ cities:[...this.state.cities.cities, ...newCities.cities], isEnd: newCities.isEnd, } }) } }); const cityDetail = new CityDetail(); this.setState = (newState) => { this.state = newState; cityList.setState(this.state.cities); header.setState({sortBy:this.state.sortBy, searchWorld:this.state.searchWorld}); }; const init = async() => { const cities = await request(this.state.startIdx, this.state.sortBy, this.state.region, this.state.searchWorld); this.setState({ ...this.state, cities: cities, //api 호출의 결과인 cities }); }; init(); }
-
해결됨한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지
컴포넌트에 매개변수 전달하는 방식에 대하여
프로젝트 작성할 때 ,APP.js와 components폴더 안의 js모듈로 보통 구성을 하시는데,왜 APP.js에서 $app을 매개변수로 받을 때는 소괄호에서 바로 받는데,다른 컨포넌트 내부 js모듈에서는 중괄호로 받는건가요? export default function App($app) {} export default function CityList({ $app, initialState,handleLoadMore }) {} APP의 경우 전달받는게 하나인데, CityList의 경우 APP에서 여러개의 매개변수를 받아오기 떄문에 구조분해로 받아오는 건가요? 만약 그렇다면 한개만 매개변수로 받아오는 경우, CityList도 (소괄호)안에 {중괄호}없이 바로 매개변수를 써도 되는 건가요?
-
해결됨한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지
require 질문드립니다.
안녕하세요! 동물앨범 수업 따라가던 중 질문이 생겨 문의드립니다.require함수 작성시 밑줄이 생기며 require is not defined라는 에러가 뜨는데, 저대로 실행을 하면 정상 작동하긴 합니다. 구글링을 해보니 package.json파일에 "type":commonJs를 추가하라고 하여 했는데도 똑같이 밑줄이 생깁니다. 어떤게 문제일까요?
-
해결됨한 번에 끝내는 자바스크립트: 바닐라 자바스크립트로 SPA 개발까지
동물앨범 3-3 express 설치 후
express 파일까지 설치하고 server.js에 코드를 작성해 주었습니다.그런데 웹을 새로고침한 경우Cannot GET /penguin이런 에러가 계속 발생합니다. 이 에러를 해결하기 위해서 express를 설치한 것 같은데..무엇이 문제인 걸까요?혹시 몰라 깃의 코드를 확인해 봤는데, 코드상 문제는 없었습니다. import Content from "./components/Content.js"; import TabBar from "./components/TabBar.js"; import { request } from "./components/api.js"; export default function App($app) { this.state = { currentTab: window.location.pathname.replace("/", "") || "all", photos: [], }; //tab const tab = new TabBar({ $app, initialState: this.state.currentTab, onClick: async (name) => { history.pushState(null, null, `/${name}`); this.updateContent(name); }, }); const content = new Content({ $app, initialState: [], }); // 상태 업데이트 함수 this.setState = (newState) => { this.state = newState; tab.setState(this.state.currentTab); content.setState(this.state.photos); }; this.updateContent = async (tabName) => { try { const currentTab = tabName === "all" ? '' : tabName; const photos = await request(currentTab); this.setState({ ...this.state, currentTab: tabName, photos:photos, }) } catch (error) { console.log(error) } }; window.addEventListener("popstate", () => { this.updateContent(window.location.pathname.replace("/", "") || "all"); }); const init = async () => { this.updateContent(this.state.currentTab); }; init(); } const express = require('express'); const path = require("path"); const app = express(); const PORT = 3000; app.use(express.static(path.join(__dirname, ".."))); app.get("/*", (req, res) => { res.sendFile(path.join(__dirname, "..", 'index.html')); }); app.listen(PORT, () => { console.log('START SERVER') })++추가질문port주소를 3000으로 변경하면 해당 오류가 발생하지 않는 것을 확인했습니다. 라이브서버를 자동으로 실행하면 port가 5500이어서 오류가 발생한 것 같습니다.1) port는 자동으로 3000으로 변경이 안되나요?2)server.js에서 port를 새로 지정해준 이유가 궁금합니다. 그대로 5500을 하면 안되나요?
주간 인기글
순위 정보를
불러오고 있어요