【问题标题】:Cancel all subscriptions and asynchronous tasks in a useEffect when using redux使用redux时取消一个useEffect中的所有订阅和异步任务
【发布时间】:2021-06-19 14:21:47
【问题描述】:

我发现了许多类似的问题,但大多数解决方案都没有 redux 解决方案。我想在从 redux 商店删除项目后调用订阅。

以下是我取消所有订阅的代码,但我不确定我的做法是否正确!

const useFetchProperty = (propertyId, refresh = false) => {
  const dispatch = useDispatch();
  const property = useSelector(state => selectPropertyById(state, propertyId));
  const isConnected = useIsConnected();

  useEffect(() => {
    let isSubscribed = true;
    if (
      isSubscribed &&
      isConnected &&
      (property === undefined || refresh === true)
    ) {
      dispatch(fetchProperty({propertyId: propertyId}));
    }
    return () => (isSubscribed = false);
  }, [dispatch, refresh, isConnected, property, propertyId]);

  return property;
};

export default useFetchProperty;

CarDesign.js

const CardDesign = ({postId}) => {
  const {t} = useContext(LocalizationContext);
  const post = useFetchProperty(postId);
  const currentLanguage = useSelector(currentAppLanguage);
  const navigation = useNavigation();

//the rest show data would be here
}

你会看到我正在使用这两个 let isSubscribed = true;return () => (isSubscribed = false);。用dispatch取消所有订阅和异步任务是否正确???

这是我遇到的那个错误的屏幕截图。

【问题讨论】:

    标签: reactjs react-native redux


    【解决方案1】:

    您的isSubscribe 变量范围在useEffect 内,因此无需执行以下操作

    return () => (isSubscribed = false);
    

    原因是 - 当你的 useEffect 将产生新的效果时,isSubscribe 将始终具有 true 因为变量声明。由于范围在 useEffect 内,因此删除返回将解决该问题

    但如果你真的需要使用它,那么在全局声明 isSubscribe 变量

    【讨论】:

    • 嗨@moshfiqrony,对不起,我不清楚如果我在全局或本地定义isSubscribe 变量,它怎么能全部订阅。我认为只定义变量不能取消所有订阅。
    • 这里的问题是。您在 useEffect 中定义 isSubscribed 变量,当调用返回时,isSubscribed 会丢失上下文或内存。所以发生的事情是它无法执行isSubscribed = false 行。因为它已经卸载了。
    猜你喜欢
    • 2021-01-28
    • 2021-03-24
    • 2020-11-28
    • 2019-10-20
    • 2020-03-31
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    相关资源
    最近更新 更多