【问题标题】:Previous data showing even though cleaning up in useEffect尽管在 useEffect 中进行了清理,但之前的数据仍显示
【发布时间】:2023-01-30 21:33:49
【问题描述】:

我的 React 本机应用程序中有一个组件可以加载与特定个人相关的会话。在该组件的 useEffect() 中,我在组件成为焦点时加载会话,并在清理过程中卸载这些会话。

export const ClientScreen = (props) => {
  const isFocused = useIsFocused();
  const client = useSelector((state) => selectActiveClient(state));
  useEffect(() => {
    if (isFocused) {
      const loadSessions = async () => {
        if (client?.id) {
          dispatch(await loadClientSessions(client?.id));
        }
        return () => dispatch(unloadSessions()); // Cleaning up here...
      };
      loadSessions(props);
    }
  }, [isFocused, client?.id]);

  const updatedProps = {
    ...props,
    client,
  };

  return <ClientBottomTabNavigator {...updatedProps} />;
};

通常,该组件按预期工作。但是,我确实注意到,如果我用一个客户端加载组件,然后导航离开,然后通过加载新客户端返回到组件,那么在被替换会话之前,与前一个客户端相关的会话会短暂显示与新客户相关。

我的问题是,在清理时运行的unloadVisits()——将会话设置为空数组——不应该阻止这种情况吗?或者这是某种保持组件先前状态的反应行为?我怎样才能确保这种行为不会发生?

【问题讨论】:

  • 您的效果不会清除任何东西。 loadSessions(props) 返回一个清理函数,但你直接忽略它。您的效果不会返回任何内容。

标签: reactjs react-native react-hooks


【解决方案1】:

Cleanup function 应该出现在 useEffect 钩子的右括号之前

useEffect(() => {
  if (isFocused) {
    const loadSessions = async () => {
      if (client?.id) {
        dispatch(await loadClientSessions(client?.id));
      }
    };
    loadSessions(props);
  }

  return () => dispatch(unloadSessions()); // Cleaning up here... // <--- here
}, [isFocused, client?.id]);

【讨论】:

  • 这可能会调用unloadSessions而无需调用loadSessions
  • 是的,谢谢,这是我在写问题时想到的。它应该在if 块之外。现在测试。
【解决方案2】:

正如所评论的那样,您的loadSessions 返回了一个清理函数,但您没有对它做任何事情。并且您调用 loadSessions(props) 的效果不会返回任何内容。

return loadSessions(props);

但你不需要 async/await 一切

useEffect(() => {
  if (isFocused && client?.id) {
    loadClientSessions(client.id).then(dispatch);

    return () => dispatch(unloadSessions());
  }
}, [isFocused, client?.id]);

【讨论】:

    猜你喜欢
    • 2017-04-22
    • 2018-12-09
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 2016-03-17
    • 2019-04-26
    • 2016-10-13
    • 2014-06-29
    相关资源
    最近更新 更多