시작하는 중
내 코드 리팩토링 하기 본문
https://github.com/vinitus/newpost_refactor
GitHub - vinitus/newpost_refactor
Contribute to vinitus/newpost_refactor development by creating an account on GitHub.
github.com
코드는 여기
간단하게 한 페이지를 리팩토링할 것이다.
이 페이지의 목적은
1. 레시피 게시글 작성이니 만큼 제목, 간단소개, 소요시간, 기준량, 재료, 만드는 단계를 제공해야한다.
2. 이미지는 멀티파트로 보내고, 텍스트들은 application/json으로 보내야한다.
3. 이미지는 드래그 앤 드롭이 가능해야하고, 이미지를 미리보기 할 수 있어야한다.
서버는 없애놨기에 API 요청은 다음과 같이 출력만 되면 된다.
그럼 시작!
1. 일단 필요없는 상태들을 지우기로 했다.
여기서 기본 코드를 볼 수 있다.
https://github.com/vinitus/newpost_refactor/tree/1-init
GitHub - vinitus/newpost_refactor
Contribute to vinitus/newpost_refactor development by creating an account on GitHub.
github.com
2. 지금은 썸네일과 요리 단계 이미지를 따로 해놔서 이것 부터 하기로 했음
https://github.com/vinitus/newpost_refactor/tree/2-remove-thumbnail-state
GitHub - vinitus/newpost_refactor
Contribute to vinitus/newpost_refactor development by creating an account on GitHub.
github.com
어떻게 했냐면, 단순하게 step과 관련된 상태들에 0번째 인덱스로써 추가하였고, 요청을 보낼 때 반복문으로 돌게 하였음
-> 썸네일은 필수라서 어차피 무조건 들어가서 그냥 넣었음
원래는 stepNums를 통해 단계를 관리했는데 1단계는 1부터 시작해서 stepNums.map 반복문의 값에서 -1 처리해줘서 단계를 관리하는 배열들의 인덱싱과 매핑했는데 -1을 빼서 처리
3. 단계를 단순한 숫자로 나타내줄 배열들이 필요 없다.
https://github.com/vinitus/newpost_refactor/tree/3-remove-the-state-associated-with-steps
GitHub - vinitus/newpost_refactor
Contribute to vinitus/newpost_refactor development by creating an account on GitHub.
github.com
복잡하게 stepNums를 하나의 상태로 관리할 필요없이, axios 요청이 일어날 newpostAPI에서 stepNums를 미리 선언해주고, 파일이 담겼고 0이 아니라면 추가하기로 했다.
orderArr도 마찬가지로 stepContent로 관리하면 필요없는 상태이다.
4. ref를 왜 써야하며 왜 배열로 관리해야할까?
ref를 썻던 이유 : div에 드래그 앤 드롭으로 파일을 업로드하면 DOM에 직접 접근하기보다는 ref로 접근하기 위함
그럼 이를 상위 컴포넌트에서 굳이 관리해줘야할까?
아니니까 잘라내고 ArticleImgBlock에서 각각 useRef를 사용하기
https://github.com/vinitus/newpost_refactor/tree/4-remove-ref-array
GitHub - vinitus/newpost_refactor
Contribute to vinitus/newpost_refactor development by creating an account on GitHub.
github.com
5. 사용하지 않는 코드 제거하고 state를 reducer로 관리하기
함수형 프로그래밍 강의 듣고 해야겟다
'react' 카테고리의 다른 글
yarn dev를 하면 vite에서 일어나는 일 (0) | 2023.05.02 |
---|---|
useState(함수)??? (0) | 2023.04.20 |
react router v6.4에 생긴 기능들 (0) | 2023.04.12 |
react-redux의 dispatch의 return은 무엇일까 (0) | 2023.03.27 |
DOM과 React의 가상 돔 (0) | 2023.03.22 |