redux 一种从ThunkAction返回退订的方法?

ws51t4hk  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(94)

有没有一种方法可以像这样从ThunkAction返回unsubscribeSnapshot的引用:

export const someFetchAction = () => async (dispatch: Dispatch, getState: GetState) => {
  let unsubscribeAuth: UnsubscribeAuth | null = null;
  let unsubscribeSnapshot: UnsubscribeSnapshot | null = null;

  try {
    // Subscribe to auth state changes
    unsubscribeAuth = getAuth().onAuthStateChanged(user => {
      // check if authenticated
    });

    // Subscribe to snapshot updates
    unsubscribeSnapshot = onSnapshot(queryRef, (docsSnapshot) => {
      // dispatches payload data and sets loaded to true
    })

    return {
      unsubscribe: () => {
        if (unsubscribeAuth && unsubscribeSnapshot) {
          unsubscribeAuth();
          unsubscribeSnapshot();
        }
      }
    }

  catch(error) {
    // dispatches error and sets flag error to true
    if (unsubscribeAuth && unsubscribeSnapshot) {
      unsubscribeAuth();
      unsubscribeSnapshot();
    }
  }
}

我尝试从React的useEffect调用它

const { loaded } = useSelector(state => ({
  loaded: state.fireReducer.loaded,
}))

const { someFetchAction } = useActions({
  someFireAction: fireActions.someFireAction,
});

useEffect(() => {
  let actionRef;
  if (!loaded) {
    actionRef = someFireAction();
  }

  return () => {
    actionRef.unsubscribe();
  }
}, [loaded])
qoefvg9y

qoefvg9y1#

你看起来并不真的需要“取消订阅”形实转换程序,而是形实转换程序中的“东西”需要取消订阅,即firebase订阅。在我看来,自定义的React钩子是一个更好的选择,因为你可以将它耦合到React组件的生命周期,例如。使用useEffect钩子的目的。
示例:

import store from '../path/to/store';

const useFirebase = (loaded: boolean) => {
  useEffect(() => {
    let unsubscribeAuth: UnsubscribeAuth | null = null;
    let unsubscribeSnapshot: UnsubscribeSnapshot | null = null;

    if (!loaded) {
      // Subscribe to auth state changes
      unsubscribeAuth = getAuth().onAuthStateChanged(user => {
        // check if authenticated
      });

      // Subscribe to snapshot updates
      unsubscribeSnapshot = onSnapshot(queryRef, (docsSnapshot) => {
        // store.dispatch payload
      });
    }

    return () => {
      if (unsubscribeAuth && unsubscribeSnapshot) {
        unsubscribeAuth();
        unsubscribeSnapshot();
      }
    }
  }, [loaded]);
};

用途:

useFirebase(loaded);

相关问题