为什么更新状态未反映在事件侦听器中:React Native,Hooks

发布时间:2020-07-07 10:03

我正在使用挂钩来更新状态。在我的代码中,我有一个AppState事件侦听器,无论何时触发,我都会使用 setAppState 更新 appState ,但是事件侦听器内部的appState并没有改变。但是该值正在侦听器外部更新。谁能解释为什么会这样?

这是我的代码:

$ openssl ec -in AuthKey.p8 -pubout -out AuthKey_public.p8
回答1

在您的代码appState中,stale closure the linter应该告诉您您缺少依赖项。

我认为以下方法会起作用

const _handleAppStateChange = useCallback(
  (nextAppState) =>
    //use callback for state setter so you don't
    //  create needless dependency or (as you did)
    //  create a stale closure
    setAppState((currentAppState) => {
      //logs current appstate
      console.log(currentAppState, 'app state');
      if (
        currentAppState.match(/inactive|background/) &&
        nextAppState === 'active'
      ) {
        console.log('App has come to the foreground!');
        activateRealtime();
      } else if (
        currentAppState === 'active' &&
        nextAppState.match(/inactive|background/)
      ) {
        console.log('App has come to background!');
      }
      return nextAppState;
    }),
  //only pass function as _handleAppStateChange
  //  on mount by providing empty dependency
  []
);
useEffect(() => {
  AppState.addEventListener(
    'change',
    _handleAppStateChange
  );
  //clean up code when component unmounts
  return () =>
    AppState.removeEventListener(
      'change',
      _handleAppStateChange
    );
  //_handleAppStateChange is a dependency but useCallback
  //  has empty dependency so it is only created on mount
}, [_handleAppStateChange]);