react 중첩 라우팅 (react-router-dom v.5)

Ell!·2021년 11월 17일
0

react

목록 보기
7/28
post-thumbnail

react-rotuer-dom을 이용한 중첩 라우팅 방법

우선 react-route-dom을 이용해서 라우팅 중첩을 시키는 방법을 먼저 알아보자.

// app.js

import React from 'react';
import {BrowserRouter as Router, Route, Switch } from 'react-router-dom'


const App = () => {

	return (

		<Router>
      		<Switch>
      			<Route path="/profile" component={Profile}/>
      		</Switch>
      	</Router>
	);

}

// profile.js

const Profile = ({match}) => {

	<Route path={`${match.path}/${userID}} component={userDetail}>

}

기본적인 사용법은 이렇게 페이지 안에 다시 route를 지정해주면 된다.

하지만 이번 프로젝트에서는 문제가 있었는데...

profile (page) -> gamelist (component) -> gameaccount(component) 의 3중첩이 이루어져있었고, 유저 자신의 프로필 / 타인의 프로필인지에 따라서 gamelist에서 직접 api호출 / profile page에서 api호출하여 props로 내려주는 두 가지 방식으로 data를 받아오고 있었다.

그리고 이전에는 state의 변화로 처리하던 gamelist를 이유가 생겨서 라우팅처리를 해줘야했다.

어떤 게임을 선택했는지 url로 나타내주어야 했다.

문제는 이 상태에서 새로고침을 하면 404 not found page가 열린다는 점이었다.

해결 방법

우선 두 가지 방법으로 문제를 해결하였다.
첫번째는 Routerender 프로퍼티를 활용하였다.

  <Route
          exact
          path={`${match.path}/:game`}
          render={({ match }) => {
            console.log(match.params.game);
            console.log(gameList);
            const currentGame = gameList.filter(
              game => game.game === match.params.game,
            )[0];
            // 컴포넌트 안의 컴포넌트에 match 새로 props로 전달
            return (
              <GameProfiles>
		...

Routecomponent를 지정해줘도 되지만 render를 통해서도 컴포넌트를 전개할 수 있다. 이 경우 직접적으로 props를 내려줄 수 있다는 장점이 있다. 이렇게 함으로써 제대로 된 url을 match props를 통해 얻을 수 있었다.

두번째는 조금 hack하게 풀었는데, 이번 프로젝트의 경우 일괄적으로 axiosInstance를 create하여 axios 요청을 하고 있었다.

그런데 게임을 클릭한 상태에서 새로고침을 하면 이 경우처럼 localhost/api가 아니라 localhost/:user/api로 요청이 갔다.

이를 해결하고자 axiosInstance에 baseUrl을 넣어보았는데 그러면 통신이 원활하지 않았다. (로그인이 풀리던가 하는 문제가 발생.)
그래서 결국

const useUserProfileQuery = (paramID, userID) => {
  console.log(paramID, userID);
  const fetchUserProfile =
    paramID === userID
      ? () => axiosInstance.get('http://111.111.111.111/api/profile/me')
      : () =>
          axiosInstance.get(`http://111.111.111.111/api/profile/${paramID}`);

  const userProfile = useQuery(['profile', `${paramID}`], fetchUserProfile, {
    refetchOnWindowFocus: false,
    refetchOnMount: true,
    refetchOnReconnect: true,
    retry: false,
    //staleTime: 60 * 60 * 1000,
  });

  return userProfile;
};

이렇게 하드코딩으로 넣어주었다 ㅠㅜㅜ

좀 더 찾아보고 다른 해결책을 찾아야겠다.

profile
더 나은 서비스를 고민하는 프론트엔드 개발자.

0개의 댓글