[Error]Cannot read properties of undefined (reading 'params') TypeError: Cannot read properties of undefined (reading 'params')

민돌·2023년 9월 24일

에러 코드

(...)
const Profile = ({ match }) => {
    const { username } = match.params;
    const profile = data[username];
    if (!profile) {
        return <div>존재하지 않는 사용자입니다.</div>
    }
  
(...)

버전5 책으로 공부를 하니 버전6 에서 바뀐 문법들이 에러가 자꾸 발생한다..

Cannot read properties of undefined (reading 'params')
TypeError: Cannot read properties of undefined (reading 'params')

에러 원인

버전6에서는 route props의 history, location 외에도 match가 더 이상 존재하지 않아 react hook을 사용해야 한단다.

에러 해결

다음과 같이 변경해주면 에러가 해결된다.

import { useParams } from 'react-router-dom'; // <<<

(...)
const Profile = ({ match }) => {
    const { username } = useParams(); // <<<
    const profile = data[username];
    if (!profile) {
        return <div>존재하지 않는 사용자입니다.</div>
    }
    
(...)








📚Reference
https://hyejin281129.tistory.com/18

0개의 댓글