领域侦听器内的状态未定义(领域和 React Native)

state inside realm listener is undefined (Realm and React Native)

我在使用 Realm 和 React Native 时遇到了以下问题。

在我的组件中,我想监听 Realm 的变化,这确实有效。但在侦听器内部,我的状态始终未定义 - 在侦听器内部设置状态后,useEffect 挂钩也不会触发。看起来侦听器中的所有内容都无法访问我的状态对象。

我需要访问侦听器内部的状态才能正确设置状态。我该怎么做?

编辑:状态似乎总是过时的。热重载后,状态正确,但始终滞后1次编辑

  const [premium, setPremium] = useState<boolean>(true);
  const [settings, setSettings] = useState<any>({loggedIn: true, userName: 'XYZ'});

  useEffect(() => {
    console.log('updated settings'); // never gets called
  }, [settings]);

  useEffect(() => {
    const tmp: any = settingsRealm.objects(MyRealm.schema.name)[0];
    tmp.addListener(() => {
      console.log(premium, settings); // both return undefined
      if (premium) {
        setSettings(tmp);
      }

      // for demonstration purposes
      setSettings(tmp);
    })
  }, []);

遇到同样问题的人:

添加一个引用状态的 useRef,并同时更新两者(!)(状态和 ref)将解决问题。现在,“premium”的所有实例(在监听器内)都必须更改为“premiumRef.current”。

https://medium.com/geographit/accessing-react-state-in-event-listeners-with-usestate-and-useref-hooks-8cceee73c559

  const [premium, _setPremium] = useState<boolean>(true);
  const [settings, setSettings] = useState<any>({loggedIn: true, userName: 'XYZ'});

  const premiumRef = useRef<boolean>(premium);
  const setPremium = (data) => {
    premiumRef.current = data;
    _setPremium(data);
  }


  useEffect(() => {
    const tmp: any = settingsRealm.objects(MyRealm.schema.name)[0];
    tmp.addListener(() => {
      if (premiumRef.current) {
        setSettings(tmp);
      }
    })
  }, []);


  [1]: https://medium.com/geographit/accessing-react-state-in-event-listeners-with-usestate-and-useref-hooks-8cceee73c559