[英]Redux saga using parameters of other instances of the class
我有四個不同的API類實例,其中三個具有相同的參數,另一個具有不同的參數。 但是,具有不同參數的類似乎使用其他三個實例的參數進行實例化。 為什么會這樣?
我有許多生成器函數(使用redux-saga),其中我作為參數傳遞一個帶有id和訪問令牌的API類的新實例。
以下是三個類似生成器之一的示例:
const watchMagazineFetchRecentArticles = function* () {
yield takeEvery(C.FETCH_RECENT_ARTICLES, fetchMagazineRecentArticles,
new APIClass(SPACE_ID_ONE, ACCESS_TOKEN_ONE))
}
這是不同的一個:
const watchPressPageArticles = function* () {
yield takeEvery(C.FETCH_PRESS_PAGE_ARTICLES,
fetchPressPageArticlesSaga, (new APIClass(SPACE_ID_TWO,
ACCESS_TOKEN_TWO)))
}
這是API類:
import prefix from 'superagent-prefix' const agent = require('superagent-use')(require('superagent')) export default class APIClass { constructor (spaceID, accessToken) { this.fetchRecentArticles = this.fetchRecentArticles.bind(this) this.fetchPressPageArticles = this.fetchPressPageArticles.bind(this) agent.use(prefix(`https://cdn.contentful.com/spaces/${spaceID}`)) agent.use(((req) => { req.header.Authorization = `Bearer ${accessToken}` req.header.Accept = 'application/json' return req })) this.instance = agent } fetchRecentArticles (numOfArticles) { return this.instance .get(`/entries?content_type=article&select-fields&order=-fields.publishDate&limit=${numOfArticles}`) .then(response => response.body) .catch(error => console.error(error)) } fetchPressPageArticles () { return this.instance .get('/entries') .then(response => response.body.items) .catch(error => console.error(error)) } }
當我調用watchPressPageArticles
函數時,我可以看到使用SPACE_ID_ONE
和ACCESS_TOKEN_ONE
參數而不是SPACE_ID_TWO
和ACCESS_TOKEN_TWO
調用網絡選項卡中的api請求。
另外值得注意的是,當我注釋掉其他函數(使用SPACE_ID_ONE
和ACCESS_TOKEN_ONE
)時,api請求使用正確的spaceID和token。
我不確定為什么傳奇沒有采用正確的論點或如何解釋這種行為。 任何想法,將不勝感激!
似乎問題不在Saga
,但在任何新的api實例中都使用相同的代理。 如果你檢查
const i1 = new APIClass('1', '1');
const i2 = new APIClass('2','2');
console.log(i1.instance === i2.instance); // true
可能的解決方法是在構造函數中實例化代理,而不是
const agent = require('superagent-use')(require('superagent'))
讓我們將代理實例化移動到constructor
:
const superagentUse = require('superagent-use');
const superagent = require('superagent');
module.exports = class APIClass {
constructor (spaceID, accessToken) {
const agent = superagentUse(superagent); // this agent will be used only in this instance
agent.use(prefix(...));
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.