从redux传奇中选择状态

问题描述 投票:1回答:1

我有一个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);
}

我也从组件发送令牌作为有效载荷的一部分。还是应该从我从传奇那里存储了令牌的用户状态中选择令牌。 Coz,似乎很费劲,选择令牌mapStateToProps,然后在我可以从传奇中选择令牌的情况下,将其与动作一起发送

reactjs redux axios redux-saga
1个回答
0
投票

我建议使用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);
  });

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

axiosInstance.post('/units', payload);
© www.soinside.com 2019 - 2024. All rights reserved.