使用带有 React + Redux 的第三方 SDK

Using a third party SDK with React + Redux

我正在使用 React + Redux 应用程序,该应用程序使用第三方 SDK 连接到 websocket、使用服务进行身份验证以及发送和接收数据。以下是使用 SDK 可以完成的一些示例:

import SDK from 'third-party';

const client = SDK.init(...);

client.connect();

client.on('auth-challenge', callback => {
    // Retrieve auth token from back-end
});

client.on('ready', () => {
    client.loadData().then(data => {
        // do something with this
    });
});

是否可以将此数据存储在我的 Redux 存储中,或者使用 Sagas 加载身份验证令牌并在数据可用后对 SDK 执行操作?

我可以想象我可以将我的商店导入此文件并使用 store.dispatch() 来请求令牌(通过 Saga),但我如何知道该令牌何时加载?这是我只需要直接 API 调用的东西吗?

我建议将异步部分作为承诺放入连接组件之一的 componentDidMount 方法中,并在收到令牌时调用调度程序。

import { askForToken } from '../my-helpers/sdk-helper;

class SomeParentComponentsContainer extends Component {
  componentDidMount(){
     const { dispatch } = this.props;
     dispatch({ type: 'GET_TOKEN' })
     // async part. Drop it if you use sagas.
     askForToken()
     .then(token => {
        dispatch({ type: 'GET_TOKEN__SUCCESS', payload: { token } })
      })
     // ----
  }

  someMethodWhichNeedsTheToken = () => {
     // this is available in any connected component now from store
     const { sdkToken } = this.props;
     ....
  }

  ...
}

const mapDispatchToProps = state => ({
  sdkToken: state && state.sdkToken
})

export default connect(mapDispatchToProps)(SomeParentComponentsContainer);

第二种选择是,如果您使用 sagas,只需将 dispatch({ type: 'GET_TOKEN' }) 部分保留在 componentDidMount 中,剩下的由 saga 完成。

sagas.js

import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'
import { askForToken } from '../my-helpers/sdk-helper;

function* fetchToken(action) {
   try {
      const user = yield call(askForToken);
      yield put({type: "GET_TOKEN__SUCCESS", token });
   } catch (e) {
      yield put({type: "GET_TOKEN__FAILS", message: e.message});
   }
}


function* mySaga() {
  yield takeEvery("GET_TOKEN", fetchToken);
}

请参阅sagas documentation了解如何设置中间件以使 saga 工作。