Skip to content

Commit

Permalink
feat: add useRedirectWithoutHistory hook
Browse files Browse the repository at this point in the history
  • Loading branch information
renbaoshuo committed Jan 19, 2025
1 parent 9b178d6 commit 85a659e
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 28 deletions.
11 changes: 11 additions & 0 deletions hooks/useRedirectWithoutHistory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { StackActions } from '@react-navigation/native';
import { router, useNavigationContainerRef, type Href } from 'expo-router';

export function useRedirectWithoutHistory() {
const rootNavigation = useNavigationContainerRef();

return (href: Href) => {
rootNavigation.dispatch(StackActions.popToTop());
router.replace(href);
};
}
21 changes: 0 additions & 21 deletions hooks/useSafePush.ts

This file was deleted.

15 changes: 8 additions & 7 deletions hooks/useSafeResponseSolve.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { RejectEnum } from '@/api/enum';
import { useCallback } from 'react';
import { Alert } from 'react-native';
import { useSafePush } from './useSafePush';

import { RejectEnum } from '@/api/enum';
import { useRedirectWithoutHistory } from '@/hooks/useRedirectWithoutHistory';

interface RejectError {
type: RejectEnum; // Type 被精简为只有 6 种,具体查看 api/enum.ts
Expand All @@ -11,12 +12,12 @@ interface RejectError {
// useSafeResponseSolve 适用于安全地处理 Axios 响应错误
// Axios 的错误对象中包含了 type 字段,这段逻辑会根据 type 的不同进行不同的处理
export const useSafeResponseSolve = () => {
const redirect = useRedirectWithoutHistory();

/**
* 处理错误的通用函数
* @param error Axios reject 抛出的错误对象
*/
const safePush = useSafePush();

const handleError = useCallback(
(error: RejectError) => {
if (!error || !error.type) {
Expand All @@ -34,7 +35,7 @@ export const useSafeResponseSolve = () => {
[
{
text: '确认',
onPress: () => safePush('/login'), // 点击确认后跳转
onPress: () => redirect('/login'), // 点击确认后跳转
},
],
{ cancelable: false },
Expand All @@ -49,7 +50,7 @@ export const useSafeResponseSolve = () => {
[
{
text: '确认',
onPress: () => safePush('/login'), // 点击确认后跳转
onPress: () => redirect('/login'), // 点击确认后跳转
},
],
{ cancelable: false },
Expand Down Expand Up @@ -82,7 +83,7 @@ export const useSafeResponseSolve = () => {
break;
}
},
[safePush],
[redirect],
);

return { handleError };
Expand Down

0 comments on commit 85a659e

Please sign in to comment.