class Saga-request 中未定义组件

class component is not defined in Saga-request

我在 Saga React 中有一个 Api-请求。请求函数放在另一个文件夹中。我想在 Saga 文件中调用它,但出现错误,未定义 ProductService。可以和Saga连接吗?方法是对的。 该功能在 Saga 页面上时有效,但当我将其转移到另一个文件夹时停止。

import ProductService from "../services/productService";

function* fetchProductById(productsInList) {      
  ProductService = new ProductService();
  const myListProducts = productsInList.payload.activity.map((item) =>
   //it's request to another file 
  ProductService.getProductByKey(item)
  );
  const res = yield call(() => Promise.all(myListProducts));
  yield put(productsInMyList(res));
}

//另一个文件夹

  export default class ProductService {
        async getProductByKey(key) {    
            const data = new URLSearchParams();
            data.append("key", key);
            const res = await this.getResource(`?${data}`);    
            return await res.json();
          } 
        }

我想是因为你的命名。导入的 class 及其实例都具有相同的名称 ProductService。您可以如下更改代码

import {call, all} from 'redux-saga/effects';
import ProductService from "../services/productService";

function* fetchProductById(productsInList) {
  const productServiceObj = new ProductService();
  const myListProducts = productsInList.payload.activity.map((item) =>
    call(productServiceObj.getProductByKey, item)
  );
  const res = yield all(myListProducts);
  yield put(productsInMyList(res));
}