Redux saga 使用其他实例的参数 class

Redux saga using parameters of other instances of the class

我有四个不同的 API class 实例化,其中三个具有相同的参数,一个具有不同的参数。但是,具有不同参数的 class 似乎是用其他三个实例的参数实例化的。为什么会这样?

我有许多生成器函数(使用 redux-saga),我在其中传入一个带有 id 和访问令牌的 API class 的新实例作为参数。

以下是三个类似生成器之一的示例:

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 class:

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 函数时,我可以看到网络选项卡中的 api 请求是使用 SPACE_ID_ONEACCESS_TOKEN_ONE 参数调用的,而不是SPACE_ID_TWOACCESS_TOKEN_TWO

还值得注意的是,当我注释掉其他函数(使用 SPACE_ID_ONEACCESS_TOKEN_ONE)时,api 请求是使用正确的 spaceID 和令牌发出的。

我不确定为什么 saga 没有接受正确的论点或如何解释这种行为。任何想法将不胜感激!

问题似乎不在 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(...));

希望对您有所帮助。