2016-11-28 4 views
3

したがって、私はApiClientヘルパーを持つ反応抑制型定型文を使用しています。それは次のようになります。私はこれを行うとき、私が得る、非コンポーネントクラスをレビュックスストアに接続することはできますか?

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

をしかし:

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() {} 
} 

は私が保護されたエンドポイントにヘッダを付加することができるようにそうように、私の認証にこれを接続したいですエラー:Cannot read property 'store' of undefined。何が起きてる?通常のクラスをレデックスストアに接続できないのはなぜですか?

更新:ここApiClientヘルパーを使用して、私のログイン機能は、です:

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

私はloadUserWithAuth関数に、店舗、またはJWTを渡すためにどちらかの方法が必要...

+0

* 'connect()':** Reactコンポーネント**をReduxストア*に接続します。単にコンストラクタ/プロパティを介してクラスへの参照を渡すことはできませんか? – CodingIntrigue

+0

@CodingIntrigueどのように? –

+0

何かのように: 'var apiClient = new ApiClient(createStore()); ....コンストラクタ(store){store.getState(); } ' – CodingIntrigue

答えて

8

connect機能は、Reactコンポーネント以外では動作しません。できることは、店舗インスタンスをクラスに渡し、store.dispatchstore.getState、およびstore.subscribeと直接電話することです。

購読する場合は、購読を停止する機能も必要です。そうしないと、ストアでクラスインスタンスへの参照が永久に保持され、メモリリークが発生します。

+0

私はストアを直接定数と呼ぶことができないことに気づいていませんでした。フラックスルータを再レンダリングせずに従来のアプリケーションコンポーネントと接続することができなかったため、これは私のアプリコンポーネントには最適です。 – ArcadeRenegade

関連する問題