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();
}
답변 1
0
안녕하세요 🙂 질문주셔서 감사합니다.
유진님이 보내주신 App.js와 RegionList.js의 코드로 실행을 해봤는데요,
오류 없이 잘 동작하는 것으로 보입니다.
도시 리스트들이 나오지 않는다면, api.js 혹은 CityList.js 파일에 오류가 있는 것으로 보이는데요,
해당 컴포넌트들에 매개변수들이 알맞게 작성되어 있는지, 순서가 올바른지 다시 한 번 확인 후
그래도 오류가 발생한다면, 전체 코드를 첨부해서 보내주세요!
감사합니다.
1
안녕하세요 🙂
보내주신 코드 확인했습니다!!
코드를 확인해보니, api.js 에서 API_URL이 잘못 설정되어있는데요,
제가 강의에서 작성한대로 알맞게 변경해주시면 문제 없이 정상 작동할 것 같습니다 :)
감사합니다.
콜백 함수 메서드 등록
0
82
2
ssr방식 경험
0
75
1
compare 함수 설명에 오해의 소지가 있어보입니다.
0
82
2
API를 비동기 처리하는 이유가 끊겨서 그런건가요?
0
96
2
DOM 트리 보는 곳
0
81
1
배열과 객체의 구조분해할당 방법이 다른 이유
0
82
2
배열 메서드가 순수 함수인지 확인하는 방법
0
72
2
콜백 함수의 매개변수로 _를 쓰는 이유가 무엇인가요?
0
71
2
콜백 함수의 매개변수는 어떻게 구분되나요?
0
59
1
호이스팅 안쓰는게 좋나요?
0
54
2
함수 선언식과 함수 표현식은 어떤 경우에 쓰면 좋나요?
0
82
2
?. 연산자는 자바스크립트 연산자인가요?
0
47
1
JS의 논리 연산자 &&, ||가 리액트의 조건부 렌더링 &&, ||인가요?
0
83
2
자바스크립트 질문
1
103
2
동물앨범만들기 1-1 api 오류
0
54
2
CityList개발-handleLoadMore함수질문
0
70
1
객체와 배열의 const 차이
0
46
1
const 객체/배열 차이
0
63
2
header 개발 새로고침 오류
0
67
2
Promise 객체
1
58
2
cityList 렌더가 안되는 문제
0
55
2
init 함수 앞에 await
1
66
2
동물 앨범 만들기 pushtState 관련
0
60
2
동물 앨범 만들기 사진 관련 문의
0
75
2





