TIL - 20191114

haileyself·2019년 11월 14일
0

1. 함수의 표현방식

함수의 표현방식은 두가지로 나뉘어진다.
1. 함수 선언식 - Function Declarations
2. 함수 표현식 - Fucntion Expressions

두 가지 표현방식에 대해서 알아 보겠다.

1) 함수선언식

일반적으로 가장 많이 쓰는 함수의 선언과 비슷한 형식

function 함수명 () {
  실행 로직
};
function TwoSum(x, y) {
  return x + y ;
};
   
  • 함수선언식은 함수의 호이스팅이 적용된다.
console.log(TwoSum(1,3)); // 출력값 : 4 

function TwoSum(x, y) {
  return x + y ;
};
//함수의 선언은 console.log 보다 아래에 되었지만, 호이스팅이 적용되어 console.log로 출력값이 나옴 !

2) 함수표현식

자바스크립트의 유연성을 활용한 선언방식

var 함수명 = function () {
  실행 로직
};
const addTwo = function (x,y) {
 return x + y;
};
  • 함수의 호이스팅에 영향 받지 않음.
console.log(addTwo(1,3)); // 에러메세지 발생 
let addTwo = function(x, y) {
	return x+y;
}

아래와 같은 에러메세지가 발생한다.

  • 다양한 활용이 가능
    (클로져, 콜백으로 사용할 수 있음)
    클로져로 사용하는 방법은 추후 공부가 필요....
  • 함수 표현식의 함수는 기명함수, 익명함수로 나누어진다.
    (1) 기명함수 (named function)
const addTwo = function sumNums (x,y) {
 return x + y;
};

(2) 익명함수 (anonymous function)

let addTwo = function(x, y) {
	return x+y;
}

2. 타입스크립트 사용시 해결한 Error

1) expected 0 arguments but got 1. 에러

map함수를 돌리고나서, argument를 함수에 받는 것으로 아래와같이 코드를 작성했더니, 해당 에러메세지가 뜨면서 렌더 안됨.

구글 검색 후 보니,
함수가 argument를 받지않는 void함수로 여겨지고 있었음.
그래서 새로 argument 와 타입을 지정해주고, parameter가 들어갈 수 있도록 조치해줌.
문제 해결 !

//렌더 함수 아래 
<CommentListWrap>
             {comments.map((el, index) => {
               return (
                 <>
                   <CommetList>
                     <CommentWrap>
                       <CommentID>
                         <CommentIDLink>{el.name}</CommentIDLink>
                       </CommentID>
                       <CommentText>{el.message}</CommentText>
                     </CommentWrap>
                     <CommentLikeBox
                       onClick={() => this.handleLikeIcon(el.id, index)} >

//constructor 아래 부분 
                 
handleLikeIcon(id: number, index: number) {
	const commentsCopy = JSON.parse(JSON.stringify(this.state.comments));
   commentsCopy[index].commentLiked = !commentsCopy[index].commentLiked;
   this.setState({ comments: commentsCopy });
 }

index와 id 값에 대해서 정확히 타입을 지정해주고 나서 해당 함수에서 parameter를 받으니깐 문제 해결 !

2) lambdas are forbidden in jsx attributes due to their rendering performance impact (jsx-no-lambda) 메세지

해당 메세지는 onClick={this.handleLikeIcon} 이렇게 작성한 코드를, 해당 이벤트를 통해 받은 index 값을 받기 위해서 arrow function 형태로 변경했더니 제목과 같은 에러 발생.

<CommentLikeBox onClick={() => this.handleLikeIcon(el.id, index)}  >

검색해보니,, jsx-no-lambda rule을 바꿔주면 된다고 나옴!

tslint.json 파일에

 "rules": {
    "jsx-no-lambda": false
  }

이렇게 적으면 에러해결~!!!

참고사이트 :
https://jonhilton.net/typescript-and-react-forbidden-lambdas/
profile
Keep on my way ! :)

0개의 댓글