타입스크립트 에러 TS2339: Property 'map' does not exist on type ''

veloger·2024년 3월 26일
0

에러 해결

목록 보기
18/18
const Main:React.FC = () => {
    type menuType={
        menu_key : String;
        menu_name : String;
        menu_level : Number;
        menu_parentKey : Number;
        menu_url : String;
        menu_createAt : String;
        menu_position : String;
        menu_seq : Number;
        menu_default : String;
    }
    type menuListType = {
        menuList : menuType[];
    }
    const [menuList, setMenuList ] =useState<menuListType>();

    useEffect(() => {
        fetch("http://localhost:8080/menu/getAllMenus.do", {
            method : "GET",
            cache : "no-cache"
        })
            .then(response => response.json())
            .then(jsonResult => {
                if(jsonResult.result === true) {
                    console.log(jsonResult.message);
                    setMenuList(jsonResult.allMenuList);
                }
            });
    }, []);

    return (
        <>
            { menuList == null || typeof menuList == undefined ? ( <div>로딩중</div> )
                                                                : (menuList.map((menu:menuType) => <div>{menu.menu_name}</div>))
            }
        </>
    );

에러

이유

TypeScript는 menuListType가 menuType[] 배열 타입을 가지고 있는지 알지 못한다.
따라서 menuList 상태가 실제로 배열이 아니라 단일 객체라고 인식하여 생기는 오류

해결방안

useState<menuListType>();  
==> useState<menuType[]>(); 로 수정

0개의 댓글