【问题标题】:How to select the state from within Redux-Saga如何从 Redux-Saga 中选择状态
【发布时间】:2020-06-01 12:06:25
【问题描述】:

我有一个 react 应用程序,我正在其中创建一个单元,它需要授权。

function* createUnitWorker(action) {
  const { payload: {unitDetails, history} } = action;
  try {
    const unit = yield axios({
      method: 'post',     
      url: `https://myBackend/units/`,
      headers: {'Authorization': 'Bearer'+token}, 
      data: {
         ...unitDetails
      }
    });
    yield put(call(createUnitSuccess, unit));
    yield history.push(`/unit/${unit.code}`)
  } catch (error) {
    yield put(createUnitFailure(error));
    yield put(history.push('/error'))
  }
}
export function* createUnitWatcher() {
  yield takeLatest(unitActionTypes.CREATE_UNIT_START, createUnitWorker);
}

我应该从组件中发送令牌作为有效负载的一部分,还是应该从存储在 saga 中的用户状态中选择令牌?因为在我看来,选择令牌 mapStateToProps 然后在我可以从 saga 中选择令牌时将其与操作一起发送是很复杂的

【问题讨论】:

    标签: reactjs redux axios token redux-saga


    【解决方案1】:

    我建议使用 axios interceptors,这样您就不必手动将令牌添加到您发送的每个请求中。

    const axiosInstance = axios.create({
      baseURL: 'https://baseUrl.com',
      headers: { "Content-Type": "application/json" }
    });
    
    axiosInstance.interceptors.request.use(function (config) {
        config.headers.Authorization = 'Bearer'+token;
        return config;
      }, function (error) {
        // Do something with request error
        return Promise.reject(error);
      });
    

    这意味着您可以只在每个 saga 中使用 axiosInstance,而不必担心令牌。像这样:

    axiosInstance.post('/units', payload);
    

    【讨论】:

      猜你喜欢
      • 2017-09-14
      • 2021-12-21
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      • 2017-11-28
      • 1970-01-01
      • 2017-09-17
      • 1970-01-01
      相关资源
      最近更新 更多