如何在React组件之外调用Zustand/React钩子?

How to call Zustand / React hook outside of React component?

提问人:jnemecz 提问时间:2/22/2023 更新时间:3/6/2023 访问量:9636

问:

我有这个Zustand商店来存储有关登录用户的真实操作信息。

const authStore = (set: any) => ({
    ...initialState,
    doLogin: async (user: TLoggedInRequest) => {
        try {
            set(() => ({status: "pending"}))
            const result = await loginService.login(user)
            set(() => ({
                status: "resolved",
                user: result?.data.user,
                error: null
            }))
        } catch (error) {
            console.log("rejected error", error)
            set((state: any) => ({status: "rejected", error}))
        }
    },
    doLogout: async () => {
        await loginService.logout()
        set(() => initialState)
        history.push("/")
    }
});

这是与REST API的通信使用Axios,GET方法的示例(为简洁起见,省略其余部分)。HTTPApiClient

async get<TResponse>(path: string): Promise<TResponse> {
    try {
        const response = await this.instance.get<TResponse>(path);
        return response.data;
    } catch (error: any) {
        handleServiceError(error);
    }
    return {} as TResponse;
}

这段代码在用户注销时在 React 组件中执行。

const doLogoutSelector = (state: any) => state.doLogout;
const doLogout = useAuthStore(doLogoutSelector);

const signout = () => {
        doLogout()
        return <Navigate replace to="/"/>
}

我想在从后端获取状态代码时注销用户。我能够识别客户端中的 401 代码,但我不知道如何调用注销钩子。HTTPApiClient401 Unathorized

Q:React 组件之外的钩子如何调用?

JavaScript 反应JS 公理 zustand

评论


答:

21赞 mleister 3/6/2023 #1

答案很简单。尝试:

useAuthStore.getState().doLogout()

我的错误拦截器如下所示:

...
if (error instanceof AxiosError && response && response.status && response.status === HTTP_STATUS_UNAUTHORIZED) {
    useAuth.getState().logout()
}
...

使用身份验证

export const useAuth = create<UseAuthProps>((set, get) => ({
    ...
    logout: async () => {
        ....
    }