캐러셀 슬라이드 리팩토링
17698 단어 projectJavaScriptReactJavaScript
이렇게 작성한 코드를 도현님께서 리팩토링을 도와주셨다
그 내용을 살펴보자면...
두개의 fetch() 받는 함수만들기
// 리팩토링 전
componentDidMount() {
const config = {
method: 'get',
};
fetch('http://10.58.6.29:8000/product?option=new&limit=12', config)
.then(response => response.json())
.then(response => this.setState({ newList: response.results }));
fetch('http://10.58.6.29:8000/product?option=sale&limit=12', config)
.then(response => response.json())
.then(response => this.setState({ saleList: response.results }));
}
옵션이 다른 두개의 API주소에서 받은 데이터를 각각의 객체형태의 saleList, newList에 넣는건데
이렇게 딱봐도 중복되는 점이 많기 때문에 아래와 같이 로직을 구현할 수 있다
// 리팩토링 결과!
findFetch(value) {
fetch(`http://10.58.6.29:8000/product?option=${value}&limit=12&order=?`)
.then(response => response.json())
.then(response => this.setState({ [value + 'List']: response.results }));
}
componentDidMount() {
this.findFetch('new');
this.findFetch('sale');
}
새로 알게 된 점!
- API주소에도 변수를 사용할 수 있다
fetch(`http://10.58.6.29:8000/product?option=${value}&limit=12&order=?`)
- 객체의 key값 동적으로 주기
`this.setState({ saleList: response.results })`
→ `this.setState({ [value + 'List']: response.results })
캐러셀 슬라이드 라디오버튼 클릭이벤트
// 리팩토링 전
handleChecked = () => {
let { currentSlide } = this.state;
if (currentSlide === 0)
this.setState({ btn01: true, btn02: false, btn03: false });
if (currentSlide === 1)
this.setState({ btn01: false, btn02: true, btn03: false });
if (currentSlide === 2)
this.setState({ btn01: false, btn02: false, btn03: true });
};
<input type="radio" name={name} onChange={this.handleRadio01} checked={btn01}/>
<input type="radio" name={name} onChange={this.handleRadio02} checked={btn02}/>
<input type="radio" name={name} onChange={this.handleRadio03} checked={btn03}/>
내가 원하는 기능은
1. 라디오버튼을 눌렀을 때 해당하는 currentSlide 로 state의 상태가 변경되는 거고
2. currentSlide의 번호에 따라 해당하는 라디오버튼만 checked=true 가 되는 것이었다
도현님이 내 코드를 보시더니
일단 handleChecked() 함수는 없애는 대신에 라디오버튼에 inline 형식으로 onChange 이벤트를 주셨다
기존의 handleChecked() 함수에 오류가 종종 생기는 문제가 있는 반면
직접적으로 currentSlide로 변경하고 checked도 바로 적용시킬 수 있었다
// 리팩토링 결과!
{
[0, 1, 2].map((radio, radioIdx) => {
return (
<input
key={radioIdx}
type="radio"
name={name}
checked={currentSlide === radio}
onChange={() => this.setState({ currentSlide: radio })}
/>
);
});
}
map() 함수에 적응하기!
Author And Source
이 문제에 관하여(캐러셀 슬라이드 리팩토링), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@beanlove97/캐러셀-슬라이드-리팩토링저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)