• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

HOC auth.js에 관한 오류 발생 시 참고 사항

22.05.12 22:53 작성 조회수 564

6

 

강사님 강의 내용과 똑같은 코드를 작성했으나 오류가 계속 생성됬는데 어찌저찌 풀어서 참고하실 분들을 위해 남깁니다

 

제가 오류가 발생한 상황(hoc/auth.js)

[강사님과 같은 코드를 작성 후 서버/클라이언트 실행 시 빈 화면이 나옴]

 

(오류 내용 : unctions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.)

- 해결책 : AuthenticationCheck 리턴 시 함수로 리턴하는 것이 아닌 JSX 컴포넌트로 리턴하라고 합니다

(참고 : https://www.inflearn.com/questions/357383)

- 실제로 auth.js의 마지막 부분인 을 return AuthenticationCheck  -> return <AuthenticationCheck />로 변경 시 정상적으로 작동함을 확인할 수 있었습니다.

 

[hoc/auth.js 코드]

import React, { useEffect } from "react";
import { useDispatch } from "react-redux";
import { auth } from "../_action/user_action";

import { useNavigate } from "react-router-dom";

export default function (SpecificComponent, option, adminRoute = null) {
  //option : null = anyone, true = login user only, false = logout user only
  function AuthenticationCheck(props) {
    const dispatch = useDispatch();

    const navigate = useNavigate();

    useEffect(() => {
      dispatch(auth()).then((response) => {
        console.log("auth? ", response);

        if (!response.payload.isAuth) {
          // login yet
          if (option) {
            navigate("/login");
          }
        } else {
          // login
          if (adminRoute && !response.payload.isAdmin) {
            navigate("/");
          } else {
            if (option === false) {
              navigate("/");
            }
          }
        }
      });
    }, []);

    return (
      <SpecificComponent /> // component return이 없으면 React 실행이 안됨.
    );
  }

  return <AuthenticationCheck />;
}

 

 

 

답변 2

·

답변을 작성해보세요.

1

공유해주셔서 감사합니다.

0

myjingu님의 프로필

myjingu

2022.07.14

감사합니다.