[英]React Router DOM v6 alternative for this.props.match.params, prevProps.match.params, this.props.location.pathname, prevProps.location.pathname
I have previously used React Router DOM v4 and the following:我以前使用过 React Router DOM v4 和以下内容:
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?我应该如何在 v6 中替换它们?
Use the useEffect
hook with dependency to replace componentDidUpdate
and the useLocation
and useParams
hooks to replace the location
and match
props.使用带有依赖关系的useEffect
挂钩来替换componentDidUpdate
,使用useLocation
和useParams
挂钩来替换location
和match
道具。
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.如果您的问题真的是关于如何将react-router-dom@6
钩子与旧的 class 组件一起使用,那么您需要创建一个自定义的高阶组件来使用钩子并注入道具。
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
.然后您可以装饰您的 class 组件并使用componentDidUpdate
生命周期方法并访问this.props.location
和this.props.params
。 Note that there isn't a match
prop now, eg this.props.match.params
is now just this.props.params
.请注意,现在没有match
道具,例如this.props.match.params
现在只是this.props.params
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.