【发布时间】: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