reactjs - React hooks - 依赖项重新运行 hooks
问题描述
我一直在为 React Hooks 遇到同样的问题而苦苦挣扎。依赖数组。我有很多应该触发和处理不同事件的钩子。例如:
useEffect(() => {
const doSomethingWith = (notification: Notifications.Notification) => {
...
setUser({ notifications: badgeCount });
};
notificationListener.current = Notifications.addNotificationReceivedListener(
(notification) => {
if (user) {
doSomethingWith(notification);
}
}
);
return () => {
Notifications.removeNotificationSubscription(notificationListener);
};
}, [setExpoPushToken, setUser, user]);
在这个简化的代码中,您可以看到我跟踪通知,当我收到通知时,我使用通知中的数据并用它更新用户对象。
但是,只要用户更新,整个事情就会运行。就像,如果我更新用户名 - 通知挂钩将运行。这对我来说意义不大。它迫使我在这些钩子函数中添加 if 语句,这是一种浪费,并使我的代码变得丑陋。
我错过了什么?我该如何更好地处理这个问题?
解决方案
推荐阅读
- firebase - 如何使用 Firebase-Cli 以编程方式为我的项目创建托管站点?
- angular - 从 Angular 6 类型错误升级 Angular 7
- java - 使用 QueryDSL 在两个不同的字段中搜索一个值
- php - 页面加载超时,刷新-codeigniter
- c++ - 将 CMake 配置为仅运行 scons,而不构建任何东西
- php - 单击提交输入按钮时如何在PHP中下载文件
- powerbi - 将 Power BI 与 OLAP 多维数据集一起使用
- android - 使用活动别名运行代码时出现安装错误
- spring - 使用 Spring Boot 进行测试批处理
- r - 在 R 中运行 1000 个置换测试以进行相关性