React Router에 추가된 Hooks
useHistory()
, useLocation()
은 이미 익숙한 history
객체와 location
객체를 받아낼 수 있고, useParams()
와 useRouteMatch()
는 조금 더 편의성을 높인 녀석들이다.
function BlogPost() {
let { slug } = useParams();
return <div>Now showing post {slug}</div>;
}ReactDOM.render(
<Router>
<Switch>
<Route exact path="/">
<HomePage />
</Route>
<Route path="/blog/:slug">
<BlogPost />
</Route>
</Switch>
</Router>,
node
);
샘플 코드에 나와있는대로 URL Params를 좀 더 간편하게 받을 수 있다.
다만, Context API를 사용하는 녀석이기 때문에 <Route>
의 하위에서만 값을 받을 수 있다.
<App>
<Router>
<Menu />
<Body>
<Switch>
<Route path="/blog/:slug" />
</Switch>
</Body>
</Router>
</App>
위와 같은 경우 <Menu/>
에서 :slug
값을 받을 수는 없기 때문에, URL Pattern Match를 통한 어떠한 처리를 하고자 하는 경우엔 사용하지 않는 것이 좋다.
import { useRouteMatch } from "react-router-dom";function BlogPost() {
let match = useRouteMatch("/blog/:slug");// Do whatever you want with the match...
return <div />;
}
URL Pattern Match 처리는 useRouteMatch()
를 사용하면 좋다.
URL Pattern을 체크하는 기능이기 때문에 Context에 얽매이지 않고 광범위하게 적용된다.
function Component({to, children}) {
const match = useRouteMatch(to);
return (
<div className={match ? 'active' : undefined}>
{children}
</div>
);
}
뭐 이런식으로 <NavLink>
와 비슷한 기능을 만들기도 간편하다.
https://velog.io/@poburi/useHistory-useLocation을-이용한-페이지-값전달
https://iamssen.medium.com/react-router에-추가된-hooks는-꽤-좋다-ef7ac17e589d
https://react.vlpt.us/react-router/05-use-router-hook.html
https://reactrouter.com/web/api/Hooks //여기 확인!!!!
const { pathname } = useLocation();
const [background, setBackground] = useState("#fff"); // 배경색
const [textColor, setTextColor] = useState("#000"); // 배경 바뀐 글자 색
const dispatch = useDispatch();
const { videoList } = useSelector((state) => state.adminVideo);
const { techList } = useSelector((state) => state.admintech);
const { principal, loadMyInfoExcution } = useSelector((state) => state.user);
useEffect(() => {
if (loadMyInfoExcution) {
if (principal === null) {
alert("로그인 후 이용이 가능합니다.");
history.push("/login");
} else {
if (pathname.includes("/admin")) {
if (principal.roles !== "ROLE_ADMIN") {
alert("접근권한이 없습니다. \n 관리자에게 문의해주세요!");
history.push("/");
}
}
}
}
}, [pathname, loadMyInfoExcution]);