是否可以将非组件类连接到 redux 存储? [英] Is it possible to connect non component Class to redux store?
问题描述
所以我使用的是具有 ApiClient 帮助程序的 react-redux 样板.它看起来像这样:
So I am using a react-redux boilerplate that has an ApiClient helper. It looks like this:
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() {}
}
我想将此连接到我的身份验证,以便我可以将标头添加到受保护的端点,如下所示:
I want to connect this to my auth so that I can prepend headers to protected endpoints, like so:
@connect(state => ({ jwt: state.auth.jwt }))
export default class ApiClient {
...
但是,当我执行此操作时,出现错误:无法读取未定义的属性 'store'
.这里发生了什么?为什么我不能将一个普通的 Class 连接到 redux store?
However, when I do this, I get the error: Cannot read property 'store' of undefined
. What's going on here? Why can't I connect a regular Class to the redux store?
更新:这是我的登录功能,它使用了 ApiClient 助手:
Update: here's my login function, which uses the ApiClient helper:
export function loginAndGetFullInto(email, password) {
return dispatch => {
return dispatch(login(email, password))
.then(() => {
return dispatch(loadUserWithAuth())
})
}
}
我需要某种方式将商店或 jwt 传递到 loadUserWithAuth
函数中...
I need some way to either pass the store, or the jwt, into the loadUserWithAuth
function...
推荐答案
connect
函数不能与 React 组件以外的任何东西一起使用.您可以做的是将您的商店实例传递给您的类并直接调用 store.dispatch
、store.getState
和 store.subscribe
.
The connect
function is not going to work with anything other than React components. What you can do is pass your store instance to your class and call store.dispatch
, store.getState
, and store.subscribe
directly.
请记住,如果您订阅了,您还应该具有取消订阅的功能,否则您的商店将永远持有对您的类实例的引用,从而造成内存泄漏.
Keep in mind that if you subscribe, you should also have functionality to unsubscribe, otherwise your store will be holding a reference to your class instance forever, creating a memory leak.
这篇关于是否可以将非组件类连接到 redux 存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!