【问题标题】:Is it possible to connect non component Class to redux store?是否可以将非组件类连接到 redux 存储?
【发布时间】:2017-04-12 09:01:13
【问题描述】:

所以我正在使用具有 ApiClient 帮助器的 react-redux 样板。它看起来像这样:

export default class ApiClient {
  constructor(req) {
    /* eslint-disable no-return-assign */
    methods.forEach((method) =>
      this[method] = (path, withCredentials, { params, data } = {}) => new Promise((resolve, reject) => {

        const request = superagent[method](formatUrl(path))

        if (withCredentials) {
          console.log('first of all, its true')
          console.log(this)
        }

        if (params) {
          request.query(params)
        }

        if (__SERVER__ && req.get('cookie')) {
          request.set('cookie', req.get('cookie'))
        }

        if (data) {
          request.send(data)
        }

        request.end((err, { body } = {}) => {

          return err ? reject(body || err) : resolve(body)

        })
      }))
    /* eslint-enable no-return-assign */
  }
  /*
   * There's a V8 bug where, when using Babel, exporting classes with only
   * constructors sometimes fails. Until it's patched, this is a solution to
   * "ApiClient is not defined" from issue #14.
   * https://github.com/erikras/react-redux-universal-hot-example/issues/14
   *
   * Relevant Babel bug (but they claim it's V8): https://phabricator.babeljs.io/T2455
   *
   * Remove it at your own risk.
   */
  empty() {}
}

我想将此连接到我的身份验证,以便我可以将标头添加到受保护的端点,如下所示:

@connect(state => ({ jwt: state.auth.jwt }))
export default class ApiClient {
  ...

但是,当我这样做时,我收到错误:Cannot read property 'store' of undefined。这里发生了什么?为什么我不能将常规 Class 连接到 redux 存储?

更新:这是我的登录功能,它使用了 ApiClient 帮助器:

export function loginAndGetFullInto(email, password) {
  return dispatch => {
    return dispatch(login(email, password))
    .then(() => {
      return dispatch(loadUserWithAuth())
    })
  }
}

我需要某种方式将 store 或 jwt 传递给 loadUserWithAuth 函数...

【问题讨论】:

  • connect():将 React 组件 连接到 Redux 存储。你不能简单地通过构造函数/属性将对你的商店的引用传递给你的类吗?
  • @CodingIntrigue 怎么样?
  • 类似:var apiClient = new ApiClient(createStore()); .... constructor(store) { store.getState(); }
  • 对不起,我对此很陌生。如果您可以创建一个更详细的答案,我将不胜感激。您在那里使用扩展运算符?
  • @CodingIntrigue 我更新了我的问题以解决这个问题......我并不关心任何一种方式,但我似乎无法弄清楚如何传递 jwt,因为它是进一步行动的结果在异步操作链上...

标签: reactjs ecmascript-6 redux react-router react-redux


【解决方案1】:

connect 函数不能与 React 组件以外的任何东西一起使用。您可以做的是将您的商店实例传递给您的班级,然后直接调用store.dispatch、store.getState 和store.subscribe。

请记住,如果您订阅,您还应该具有取消订阅的功能,否则您的商店将永远持有对您的类实例的引用,从而造成内存泄漏。

【讨论】:

  • 我没有意识到我可以直接调用存储常量。这非常适合我的应用组件,因为我无法在不导致通量路由器重新渲染的情况下与应用组件进行传统连接。
  • @ArcadeRenegade 你介意告诉我你是怎么做的吗?
猜你喜欢
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 2021-01-01
  • 2018-08-28
  • 1970-01-01
  • 1970-01-01
  • 2020-11-01
  • 1970-01-01
相关资源
最近更新 更多