问题描述
我在 Saga React 中有一个 Api 请求。请求函数放在另一个文件夹中。我想在 Saga 文件中调用它,但出现错误,未定义 ProductService。能和佐贺连接吗?方法是对的。 该功能在 Saga-page 上时有效,但当我将其转移到另一个文件夹时停止。
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();
}
}
解决方法
我想是因为你的名字。您拥有同名 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));
}