redux 如何在 Saga 文件中使用自定义钩子函数?

rn0zuynd  于 2023-06-30  发布在  其他
关注(0)|答案(1)|浏览(132)

我在使用我的redux Saga 在这里的customHooks有麻烦。我是新的redux Saga 所以不能让我的头左右调用自定义钩子函数在这里。
我创建了一个自定义钩子来调用我的API函数,其中有一个函数userLogin。现在,我希望在 Saga 文件中调用相同的函数,每次发生特定的分派操作时都调用。
正确的方法是什么。我不应该在自定义钩子中定义我的API函数吗?

useApi.js

//useApi custom hook
export const useApi = () => {

    const api = useAxios();

    const userLogin = async (body, config = {}) => {
        const res = await api.post(LOGIN, body, config);
        return res.data;
    };

    return {
        userLogin,
    };
}

userSaga.js

import { takeEvery } from 'redux-saga/effects';

export function* userLoginFunction() {
    //how can I call my custom hook function here ?
    //because according to hooks rules, I cann't use the hook here.
    
    try {
       
    } catch (e) {
        
    }
}
export default function* rootSaga() {
    yield takeEvery('USER_LOGIN', fetchNumberSaga);
}
kmynzznz

kmynzznz1#

你不能... React钩子只能在React functional components内部使用。
但别🙌担心
相反,您可以创建普通的API函数并使用它们。
示例:

API.js

export const api = axios.create({ baseURL: 'https://your-api.com/api/v1' })

user-api.js

import { api } from './api'

export const signIn = async ({ credentials }) => {
  const { data: user } = await api.request({
    method: 'POST',
    url: '/sign-in',
    // ... other params
  })

  return user
}

userSaga.js

import { takeEvery, call } from 'redux-saga/effects';
import { signIn } from './user-api';

export function* userSignInWorker(action) {
  try {
    const user = yield call(signIn, { credentials: action.payload })
    // ... your code
  } catch (e) {
    // ... error handling
  }
}

export default function* rootSaga() {
  yield takeEvery('USER_LOGIN', userSignInWorker)
}

相关问题