Sungtt

배열을 map()으로 렌더링해줄 때 오류 본문

React

배열을 map()으로 렌더링해줄 때 오류

sungtt 2022. 1. 27. 19:55

오류내용 :  Array.prototype.map() expects a return value from arrow function 

 

 

렌더링하려던 배열의 콘솔을 찍어보면 배열안에 객체가 들어있는 방식이었다.

 

배열안의 객체

 

나는 화살표함수를 쓰면서 버릇처럼 () => {} 의 양식을 통해 작성하고있었다. 작성하던 코드는 아래와 같다.

      {viewContent.map((i,index)=>{
                <div key={index}>
          <h2>{i.title}</h2>
          <div>{i.content}</div>
        </div>
      })}

 

그런데 오류가 계속 나길래 확인해보니, 화살표 함수를 통해 정확히 return을 받기위해선 두가지 방법이 있었다.

 

첫번째 방법은 중괄호내부에서 return을 명시해주는 방법

두번째 방법은 실행함수를 중괄호 대신 소괄호로 감싸는 방법이 있다.

 

const arr = [1,2,3];
console.log(arr.map((i)=> {i + 3})); // => [ undefined, undefined, undefined ]
console.log(arr.map((i)=> i + 3)); // => 4,5,6 
console.log(arr.map((i)=> {return i + 3})); // => 4,5,6 
console.log(arr.map((i)=> (i + 3))); // => 4,5,6

3번째줄 코드의 경우에는 return값이 없는데도 정상적으로 출력되고있다.

그것은 화살표함수의 내용이 return뿐일때는 return과 중괄호까지 생략할 수 있기때문이다.

 

위의 내용을 토대로 코드를 수정하여서 해결되었다.

//화살표함수를 소괄호로 감싸기
	  {viewContent.map((i,index)=>(
                <div key={index}>
          <h2>{i.title}</h2>
          <div>{i.content}</div>
        </div>
      ))}


//화살표함수를 중괄호, return()으로 감싸기
      {viewContent.map((i,index)=>{
        return (
                <div key={index}>
          <h2>{i.title}</h2>
          <div>{i.content}</div>
        </div>
        );
      })}
Comments