首页 > 解决方案 > 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 语句,这是一种浪费,并使我的代码变得丑陋。

我错过了什么?我该如何更好地处理这个问题?

标签: reactjsreact-native

解决方案


推荐阅读