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
을 사용하려면 컴포넌트가 모두 렌더링이 된 후 실행해주어야한다.
useEffect(() => {
console.log('Router pathname ??? ', Router.pathname);
}, []);
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 props
와 router.asPath
를 console.log에 찍어보았다.
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; // 깔끔해짐