编程语言
首页 > 编程语言> > javascript – Redux saga使用该类的其他实例的参数

javascript – Redux saga使用该类的其他实例的参数

作者:互联网

我有四个不同的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’))

让我们将代理实例化移动到构造函数中:

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(...));

希望能帮助到你.

标签:javascript,generator,react-redux,redux-saga,superagent
来源: https://codeday.me/bug/20190701/1346695.html