[Error - Router.pathname 사용]No router instance found

마데슾 : My Dev Space·2020년 6월 15일
1
import Router from 'next/router';

const { pathname } = Router.pathname;

<Row className="main-content" gutter={8}>
  {pathname === '/profile' ? (
    <>
      <Col className="center" xs={24} md={12}>
        {children}
      </Col>
    </>
  ) : (
    <>
      <Col className="fixed left" xs={24} md={6}>
        <Meinfo />
      </Col>
      <Col className="center" xs={24} md={12}>
        {children}
      </Col>
      <Col className="fixed right" xs={24} md={6}>
        <Hottest />
      </Col>
    </>
  )}
</Row>

위와 같이 Router.pathname 값을 이용해 분기를 해주려고 했는데 아래와 같은 에러가 떴다.

에러가 발생한 이유는, Router가 컴포넌트 렌더링이 되기 전에 실행되었기 때문이다..!

그래서 Router.pathname을 사용하려면 컴포넌트가 모두 렌더링이 된 후 실행해주어야한다.

방법 1. useEffect 사용

useEffect(() => {
  console.log('Router pathname ??? ', Router.pathname);
}, []);

방법 2. widthRouter 사용

useEffect안에서 Router를 불러오는 방법도 있지만 widthRouter를 사용하는 것이 더 깔끔한거 같아 아래와같이 해보았다.

import Router, { withRouter } from 'next/router';

const AppLayout = ({ children, router }) => {
  const pathname = router.asPath;
  console.log('router ? ', router);
  console.log('pathname ? ', pathname);

  return (
    <MainWrap>
      <Row className="main-content" gutter={8}>
        {pathname === '/profile' ? ( // point 1
          <>
            <Col className="center" xs={24} md={12}>
              {children}
            </Col>
          </>
        ) : (
          <>
            <Col className="fixed left" xs={24} md={6}>
              <Meinfo />
            </Col>
            <Col className="center" xs={24} md={12}>
              {children}
            </Col>
            <Col className="fixed right" xs={24} md={6}>
              <Hottest />
            </Col>
          </>
        )}
      </Row>
    </MainWrap>
  );
};

export default withRouter(AppLayout); // point 2

router propsrouter.asPath를 console.log에 찍어보았다.

방법 3. useRouter 사용

import Router, { useRouter } from 'next/router';

const AppLayout = ({ children }) => {
  const router = useRouter();
  const { pathname } = router;

  console.log('router ? ', router);
  console.log('pathname ? ', pathname);

  return (
    <MainWrap>
      <Row className="main-content" gutter={8}>
        {pathname === '/profile' ? (
          <>
            <Col className="center" xs={24} md={12}>
              {children}
            </Col>
          </>
        ) : (
          <>
            <Col className="fixed left" xs={24} md={6}>
              <Meinfo />
            </Col>
            <Col className="center" xs={24} md={12}>
              {children}
            </Col>
            <Col className="fixed right" xs={24} md={6}>
              <Hottest />
            </Col>
          </>
        )}
      </Row>
    </MainWrap>
  );
};

export default AppLayout; // 깔끔해짐

참고블로그

profile
👩🏻‍💻 🚀

0개의 댓글