javascript - 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 方法,如果用户同时按下两个按钮,可能会运行在平行下。
为了解决这个异步问题,将钩子逻辑移动到上下文提供程序是一个不错的选择吗?
还有其他方法吗?
解决方案
您可以使用上下文,但更简单的方法是将 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();
推荐阅读
- sql - 这是最优的吗?
- java - 启动 IDEA intellij 时出错
- sql - SQL SELECT 语句是如何工作的?
- android - 将自定义 JAR 库添加到 Android 项目时 Delphi10.2 中的编译器错误
- javascript - 为什么`this`返回Window而不是元素?
- node.js - 解析云代码函数响应成功不是函数
- apache-spark - 如何使用 Spark 中的 RowKeys 列表从 Hbase 进行并行读取
- dart - 从 FireStore Flutter Firebase 数据库中另存为字符串
- c# - 了解 C# 随机变量生成
- mysql - 无法将 mySQL 连接到 Sphinx 搜索