我正在更新一个Reaction项目的包,该包已经用react-router-dom v5
实现了.我已经把react-router-dom
更新到v6
了.我在很多components
中使用了this.props.history
,因此我不需要更改它的 struct ,所以我决定创建一个具有该功能的包装器,并将组件作为props 传递给它,这样就不会更改太多代码.包装是这样的:
import * as React from 'react';
import { useLocation, useNavigate, useNavigationType, useParams } from "react-router";
export function withRouter(Child) {
return (props) => {
const [callBack,setCallBack] = React.useState();
const location = useLocation();
const navigate = useNavigate();
const action = useNavigationType();
const params = useParams();
const match = {
params: params
}
const history = {
push: (url, onMount) => {
if (onMount)
setTimeout(() => navigate(url), 100)
else
navigate(url);
},
listen: (callback) => {
setCallBack(callback);
}
}
React.useEffect(() => {
if (callBack) {
callBack(location,action)
}
}, [location])
return <Child {...props} history={history} location={location} match={match} />;
}
}
我在如下所示的组件中使用了包装器:
function action(params) {
return (
<Layout {...params}>
<PageInfo title={Utils.i18n('notificationList', true)} icon="ti-bell"/>
<NotificationList {...params}/>
</Layout>
)
}
export default withRouter(action);
下面是包装组件的componentDidMount
上的listen
函数:
componentDidMount(): void {
this.props.history.listen((location, action) => {
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
if (params.id) {
this.setState({id:params.id})
}
});
this.getNotification();
Utils.scrollToTop();
}
我在这次更新中遇到的问题是react-router-dom v5
中存在的listen
个功能.因为在Child
props 中的任何状态更改之后,所有状态都被清除,所以callBack
总是未定义的,并且我不能在我的wrapper
中实现listen
功能.在这部分代码中,回调始终未定义:
React.useEffect(() => {
if (callBack) {
callBack(location,action)
}
}, [location])
有谁有办法在我的包装器中实现listen
个功能?