I have previously used React Router DOM v4 and the following:
componentDidUpdate(prevProps) {
if ((prevProps.match.params[0] !== this.props.match.params[0])) {
...some code
}
}
componentDidUpdate(prevProps) {
if (this.props.location.pathname !== prevProps.location.pathname){
this.loadContent();
}
}
how should I replace them in the v6?
Use the useEffect hook with dependency to replace componentDidUpdate and the useLocation and useParams hooks to replace the location and match props.
Example:
import { useEffect } from 'react';
import { useLocation, useParams } from 'react-router-dom';
...
const{ pathname } = useLocation();
const {/* destructured param */} = useParams();
useEffect(() => {
loadContent();
}, [pathname]);
useEffect(() => {
...some code
}, [/* destructured param */]);
If your question is really about how to use the react-router-dom@6 hooks with an older class component, then you'll need to create a custom Higher Order Component to use the hooks and inject the props.
Example:
import {
useLocation,
useParams,
/* other hooks */
} from 'react-router-dom';
const withRouter = Component => props => {
const location = useLocation();
const params = useParams();
// other hooks
return (
<Component
{...props}
{...{ location, params, /* other hook props */ }}
/>
);
};
export default withRouter;
Then you can decorate your class component and use the componentDidUpdate lifecycle methods and access this.props.location and this.props.params. Note that there isn't a match prop now, e.g. this.props.match.params is now just this.props.params.