所以我使用的是带有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
。这里发生了什么?为什么我不能将常规类连接到redux商店?
更新:这是我的登录功能,它使用ApiClient助手:
export function loginAndGetFullInto(email, password) {
return dispatch => {
return dispatch(login(email, password))
.then(() => {
return dispatch(loadUserWithAuth())
})
}
}
我需要一些方法将商店或jwt传递到loadUserWithAuth
函数......
答案 0 :(得分:18)
connect
函数不能用于React组件以外的任何其他功能。您可以做的是将商店实例传递到您的班级,然后直接致电store.dispatch
,store.getState
和store.subscribe
。
请记住,如果您订阅,您还应具有取消订阅的功能,否则您的商店将永远保留对您的类实例的引用,从而造成内存泄漏。