有没有一种方法可以像这样从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])
1条答案
按热度按时间qoefvg9y1#
你看起来并不真的需要“取消订阅”形实转换程序,而是形实转换程序中的“东西”需要取消订阅,即firebase订阅。在我看来,自定义的React钩子是一个更好的选择,因为你可以将它耦合到React组件的生命周期,例如。使用
useEffect
钩子的目的。示例:
用途: