Javascript 在卸载组件时,重置Redux数据
应用程序中的每个我的页面都包含排序选择选项。某些页面具有预选的默认排序选项:Javascript 在卸载组件时,重置Redux数据,javascript,reactjs,redux,react-redux,Javascript,Reactjs,Redux,React Redux,应用程序中的每个我的页面都包含排序选择选项。某些页面具有预选的默认排序选项:排名。但是,当我输入一个特定组件并更改排序类型时,例如latest。如果我导航到另一个特定页面,我必须将其重置为排名 下面是我的做法: const Events = ({ history }) => { const dispatch = useDispatch(); const { sorting } = useSelector(({ filters }) => filters); useEff
排名
。但是,当我输入一个特定组件并更改排序类型时,例如latest
。如果我导航到另一个特定页面,我必须将其重置为排名
下面是我的做法:
const Events = ({ history }) => {
const dispatch = useDispatch();
const { sorting } = useSelector(({ filters }) => filters);
useEffect(() => {
dispatch(getEvents(sorting));
return () => {
history.listen(location => {
if (location.pathname !== '/events') {
dispatch({ type: 'UPDATE_SORTING_TYPE', payload: 'ranking' });
}
});
};
}, [sorting]);
return (
<Wrapper>
{/* more jsx here */}
</Wrapper>
);
};
export default withRouter(Events);
因为并非所有页面都具有默认排序类型排名
。
如何在卸载组件之前处理重置排序选项的正确方法?如果使用react router,则可以使用
useLocation
监视url更改
const location = useLocation()
useEffect(()=> {
// here you code
},[location]]
如果使用react路由器,则可以使用
useLocation
监视url更改
const location = useLocation()
useEffect(()=> {
// here you code
},[location]]
您仅在
卸载时附加侦听器。这样一来,它第一次不执行侦听器,而是在后续侦听器上执行。此外,每次卸载该组件时,都会添加几个侦听器
我认为您应该将您的历史记录onMount
附加到另一个useffect
,添加到变量unlisten
。然后返回unlisten
,在unMount
上删除侦听器:
useEffect(() => {
const unlisten = history.listen(location => {
if (location.pathname !== '/events') {
dispatch({ type: 'UPDATE_SORTING_TYPE', payload: 'ranking' });
}
});
return unlisten
}, []);
您仅在卸载时附加侦听器。这样一来,它第一次不执行侦听器,而是在后续侦听器上执行。此外,每次卸载该组件时,都会添加几个侦听器
我认为您应该将您的历史记录onMount
附加到另一个useffect
,添加到变量unlisten
。然后返回unlisten
,在unMount
上删除侦听器:
useEffect(() => {
const unlisten = history.listen(location => {
if (location.pathname !== '/events') {
dispatch({ type: 'UPDATE_SORTING_TYPE', payload: 'ranking' });
}
});
return unlisten
}, []);
嘿@s97712,是的,我确实使用react路由器
。你能详细说明你提出的解决方案吗?嘿@s97712,是的,我确实使用react路由器
。你能详细说明你提出的解决方案吗?