首页 > 解决方案 > ReactJS Async - 使用 React Context 模拟单例?

问题描述

我目前有一个钩子:

function useFollowUser() {
    const isFollowing = useRef(false);

    return (userId) => {
       if(isFollowing.current) return; // mutual exclusion

       isFollowing.current = true;

       ... update DB and GUI

       isFollowing.current = false;
    }
}

然后,我在 FollowButton 组件中使用它

function FollowButton({ userId }) {
   ...
   
   const followUser = useFollowUser();

   const handleOnPress = () => followUser(userId);
  
   return <Button onPress={handleOnPress} text=... />
}

问题是,如果在同一个屏幕我有两个相同组件的实例,具有相同的 userId 属性,会有一些数据不一致,作为 followUser 方法,如果用户同时按下两个按钮,可能会运行在平行下。

为了解决这个异步问题,将钩子逻辑移动到上下文提供程序是一个不错的选择吗?

还有其他方法吗?

标签: javascriptreactjsreact-native

解决方案


您可以使用上下文,但更简单的方法是将 isFollowing 包装到具有自执行功能的相同范围内。注意立即调用该函数的两个括号。

 const useFollowUser = (() => {
      let isFollowing = false;
    
      return () => {
     // this is hook context, you can use any effects here

        return (userId) => {
          if (isFollowing) return; // mutual exclusion
    
          isFollowing = true;
    
          // ... update DB and GUI
    
          isFollowing = false;
        };
      }
    })();

用法:

const followUser = useFollowUser();

推荐阅读