Javascript 비동기, React

냐하호후·2022년 4월 19일
0

REACT

목록 보기
2/3

promise

  • Pending (대기)
new Promise(function(resolve,reject){
//...
})
  • Fullfilled (이행)
new Promise(function(resolve,reject){
resolve();
})

then()을 이용해서 결과 값을 받을 수 있다

const promise1 = new Promise(function(resolve,reject){
resolve('성공!');
});

promise1.then((value)=>{
console.log(value); //'성공!'
})
  • Rejected (실패)
new Promise(function(resolve,reject){
reject();
})

catch()로 실패한 결과 값을 받을 수 있다

const promise2 = new Promise(function(resolve,reject){
reject('실패!');
});

promise2.then.catch(function(err){
  console.log(err); // '실패!'
})

promise를 직접 만드는 방법과 async await을 쓰는 방법은 작성하는 방식이 다를 뿐 반환하는 값이 프로미스 객체라는 점은 같다.

리액트에서 내가 만든 컴포넌트가 실행되고나서 왜 또 컴포넌트가 호출이될까

function User() {
  //로딩중 -> true, 데이터를 받아오면 false
  const [isLoading, setIsLoading] = useState(true);
  const [userData, setUserData] = useState([]);

  //axios를 이용해 데이터를 불러오고 난 후에 유저정보를 상태에 넣어준다
  let getUserInfo = async () => {
    try {
      let res = await axios.get('https://randomuser.me/api?results=20');
      if (res) {
        //응답이 있는 경우에 로딩상태가 아니다.
        setIsLoading(false);
        setUserData(res.data.results);
      }
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getUserInfo();
  }, []);

  return (
    <Box>
      {userData.map(el => {
        return (
          <div>
            <MiniTitle>고객 리스트</MiniTitle>
            <Lastname>이름</Lastname>
            <Lastname>번호</Lastname>
            <Lastname>이메일</Lastname>
            <Lastname>사는 지역</Lastname>
          </div>
        );
      })}
    </Box>
  );
}
export default User;

리액트의 Strict Mode는 부작용 검사를 한다.
1. 렌더링 단계
render 함수를 호출해서 이전렌더와 결과값을 비교한다.

  1. 커밋 단계
    componentDidMount,componentDidupdate같은 생명주기 메서드를 실행한다.

이중호출(Double-invoke)되는 함수

  • 클래스 컴포넌트의 constructor, render 그리고 shouldComponentUpdate
  • 클래스 컴포넌트의 getDrivedStateFromProps static 메서드
  • 함수 컴포넌트 바디
  • State updater 함수(setState 의 첫 번째 인자)
  • useState, useMemo, useReducer 에 전달되는 함수

useState를 쓰면 strictMode가 해당 컴포넌트를 두번 실행한다.

느낀 점

구글에 재할당을 검색하니 reallocation이라고 나왔다.
reallocation을 집어넣어서 재할당의 장점에 대해 찾아봤는데 아무리 찾아도 나오지않았다. 원인은 프로그래밍에서 사용하는 재할당은 reallocation이 아니라 reassigning이었기 때문이다 ㅎ

내가 모르는 것을 모르는 상태를 해결해야할 것같다.
무엇을 모르는지 알고 모르는 것들을 하나하나 공부해나가자!

참고

const를 씁시다
useState를 사용한 함수형 컴포넌트는 왜 2번 실행될까?

profile
DONE is better than PERFECT

0개의 댓글