: 기존 Route로 사용되지 않은 컴포넌트에서 match, location, history 객체에 접근하려면 withRouter
HOC로 컴포너트를 감싸줘야 했다.
const Post = ({ match {) => {
const { test } = match.params
}
export default withRouter(Post);
v5.1 부터 useParams
hook이 추가되면서 match.params 객체에 접근할 수 있다.
import { useParams } from 'react-routr';
const Post = () => {
const { test } = useParams();
}
export default Post
import { useHistory } from 'react-routr';
const Post = () => {
const history = useHistory();
}
export default Post
import { useLocation } from 'react-routr';
const Post = () => {
const location = useLocation();
}
export default Post
// before
import { Route } from 'react-router-dom'
function App() {
return (
<div>
{/* ... */}
<Route
path="/BLOG/:slug/"
strict
sensitive
render={({ match }) => {
return match ? <BlogPost match={match} /> : <NotFound />
}}
/>
</div>
)
}
// after
import { useRouteMatch } from 'react-router-dom'
function App() {
let match = useRouteMatch({
path: '/BLOG/:slug/',
strict: true,
sensitive: true
})
return (
<div>
{/* ... */}
{match ? <BlogPost match={match} /> : <NotFound />}
</div>
)
}