-
[Redirect, useHistory] 리액트 v6에서 없어졌다.React 2022. 9. 22. 21:12
[클론코딩 트위터] 104p 코드이다.
// import { useState } from "react";import { HashRouter as Router,Redirect, Route, Routes } from "react-router-dom";import Auth from "routes/Auth";import Home from "routes/Home";import Profile from "routes/Profile"import Navigation from "./Navigation";
const AppRouter = ({isLoggedIn}) => {// const [isLoggedIn, setIsLoggedIn] = useState(true);return (<Router>{isLoggedIn && <Navigation/>}<Routes>{isLoggedIn ? (<><Route path="/" element={<Home />} /><Route path="/profile" element={<Profile />} /></>) : (<Route path="/" element={<Auth/>} />)}<Redirect from ="*" to="/" /></Routes></Router>);};
export default AppRouter;문제점 :
위 코드를 실행하면 Attempted import error: 'Redirect' is not exported from 'react-router-dom' (imported as 'Redirect').
ERROR in ./src/components/Router.js 59:37-45 이라는 에러 메세지가 뜬다.또한 107p에서도 useHistory를 사용하는데 같은 에러 메세지가 뜬다.이유 :
리액트 v6부터 <Redirect />, useHistory는 사라졌다.
Redirect가 사라지고 Routes안에는 Route만 사용한다.
useHistory가 사라지고 useNavigate를 사용한다.
수정 코드 :
Router.js 파일
// import { useState } from "react";import { HashRouter as Router, Route, Routes } from "react-router-dom";import Auth from "routes/Auth";import Home from "routes/Home";import Profile from "routes/Profile"import Navigation from "./Navigation";
const AppRouter = ({isLoggedIn}) => {// const [isLoggedIn, setIsLoggedIn] = useState(true);return (<Router>{isLoggedIn && <Navigation/>}<Routes>{isLoggedIn ? (<><Route path="/" element={<Home />} /><Route path="/profile" element={<Profile />} /></>) : (<Route path="/" element={<Auth/>} />)}</Routes></Router>);};
export default AppRouter;Profile.js 코드
// import { useState } from "react";import { HashRouter as Router, Route, Routes } from "react-router-dom";import Auth from "routes/Auth";import Home from "routes/Home";import Profile from "routes/Profile"import Navigation from "./Navigation";
const AppRouter = ({isLoggedIn}) => {// const [isLoggedIn, setIsLoggedIn] = useState(true);return (<Router>{isLoggedIn && <Navigation/>}<Routes>{isLoggedIn ? (<><Route path="/" element={<Home />} /><Route path="/profile" element={<Profile />} /></>) : (<Route path="/" element={<Auth/>} />)}</Routes></Router>);};
export default AppRouter;파일을 위와 같이 수정하면 로그아웃 버튼을 클릭하면 url이 /로 이동하는 것을 볼 수 있다.'React' 카테고리의 다른 글