简体   繁体   English

React hooks,卸载组件时,重置Redux数据

[英]React hooks, when unmounting component, reset Redux data

Each of my pages in the app contains sorting select options.我在应用程序中的每个页面都包含排序 select 选项。 Some of the pages have a preselected default sorting option: ranking .一些页面有一个预选的默认排序选项: ranking However, when I enter one specific component and change the sorting type eg.但是,当我输入一个特定组件并更改排序类型时,例如。 latest . latest的 . After if I navigate to another specific page, I have to reset it to ranking .如果我导航到另一个特定页面,我必须将其重置为ranking

Here's how I do it bellow:这是我如何做到的:

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);

This seemed to be working fine, however, when I start the application and go to this page component, I'm changing the sorting type to latest , I navigate to another page, the listener is not triggered the first time, but only every other time I go back and repeat this process, except the first time这似乎工作正常,但是,当我启动应用程序和 go 到这个页面组件时,我将排序类型更改为latest ,我导航到另一个页面,侦听器不是第一次触发,而是每隔一个触发时间我 go 回来并重复这个过程,除了第一次

Notice: I can't reset the sorting type in my reducer on location change, like this:注意:我无法在位置更改时重置减速器中的排序类型,如下所示:

case '@@router/LOCATION_CHANGE': {
  return {
    ...state,
    sorting: 'ranking',
  };
}

Because not all pages have default sorting type ranking .因为不是所有的页面都有默认的排序类型ranking How to handle the correct way of resetting the sorting option before component unmounts?如何在组件卸载之前处理重置排序选项的正确方法?

if you use react-router you can use useLocation to watch url change.如果你使用 react-router 你可以使用useLocation来观察 url 的变化。

const location = useLocation()
useEffect(()=> {
  // here you code
},[location]]

You are attaching a listener only on unMount .您仅在unMount上附加了一个侦听器。 This way the first time it doesn't execute the listener but executes on subsequent ones.这样第一次它不会执行侦听器,而是在后续的侦听器上执行。 Also, you would be adding several listeners, for every time you unMount that component.此外,每次unMount该组件时,您都会添加多个侦听器。

I would say that you should attach your history onMount on another useEffect , adding to a variable unlisten .我会说你应该将你的历史onMount附加到另一个useEffect上,添加到一个变量unlisten Then you would return unlisten to remove listener on unMount :然后您将返回unlisten以删除unMount上的侦听器:

  useEffect(() => {
    const unlisten = history.listen(location => {
        if (location.pathname !== '/events') {
          dispatch({ type: 'UPDATE_SORTING_TYPE', payload: 'ranking' });
        }
      });

    return unlisten
  }, []);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM