[TIL] React & JS Algorithms
Async in useEffect Hook
useEffect를 사용할 때 이렇게 작성하면 안된다.
side effect 에러가 발생하기 때문.
useEffect(async () =>{
await axios.get(URL)
}
올바른 방법
- useEffect 안에서 async 함수를 선언하고 호출하기/또는 Promise 부분을 별도의 함수로 만들어 useEffect 내부에서 호출하기
useEffect(() => {
const search = async () => {
await axios.get(URL)
}
search();
}, [])
- 즉시 실행 함수로 실행하기
useEffect(()=>{
(async () => {
await axios.get(URL)
})()
}, [])
- .then 사용하기
useEffect(() => {
axios.get(URL)
.then((response) => {
console.log(response.data)
})
}, [])
JS Algorithms - sort()
sort()는 배열을 정렬하는 메서드
array.sort(compareFunc())
compareFunc()는 정렬 순서를 정하는 함수인데 없을 때 배열의 요소들은 문자열로 받아들여져 유니코드 값 순서대로 정렬된다.
compareFunc() 안에는 a,b 파라미터를 입력받아 해당 함수의 리턴값이 0보다 작으면 a가 b보다 앞에, 0보다 클 경우 b가 a보다 앞에 오도록 정렬한다. 리턴값이 0이라면 a와 b의 순서는 바뀌지 않는다.
// 배열 안 요소들을 알파벳 순서대로 나열하시오.
const list = ['Grape', 'apple', 'CHERRY', 'banana'];
const listMapped = list.map((el, i) => {
return {i, value:el.toLowerCase()}
}) // 배열 안 요소들을 소문자로 바꾼 후 객체에 넣어주고, 인덱스를 지정
listMapped.sort((a,b) => (a.value > b.value) || (a.value === b.value) - 1) // value를 알파벳 순서로 정렬
const result = listMapped.map((el) => list[el.i]) // 객체로 바꿨던 것들을 처음 상태로 복구
//console.log(result)
// 배열을 입력했을 때 알파벳 순서대로 나열해주는 함수 만들기
function solution(arr) {
const mappedArr = arr.map((el, index) => {
return { index, value:el.toLowerCase()}
})
mappedArr.sort((a,b) => {
if(a.value > b.value) return 1
if(a.value < b.value) return -1
else return 0
})
const result = mappedArr.map((el) => arr[el.index])
return result
}
solution(['Grape', 'apple', 'CHERRY', 'banana'])
Author And Source
이 문제에 관하여([TIL] React & JS Algorithms), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@jamieecode/TIL-React-JS-Algorithms저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)