当前位置: 首页 > 知识库问答 >
问题:

如何在不重复的情况下使用异步存储?

齐志勇
2023-03-14

我正在使用redux saga。执行分派时,会执行likePost和addPost等函数。

然后每次我使用异步存储。获取令牌的getItem。换句话说,它是重叠的

      const token = yield AsyncStorage.getItem('tokenstore');

因为我必须使用jwt令牌

     {},
        {
          headers: {Authorization: `Bearer ${token}`},
        },

我需要不断传递这样的头到api。这也是重叠

这个怎么用没有冗余,或者说怎么用最方便?

这是我的密码

(saga/post.js)

    import {all, fork, put, takeLatest, throttle, call} from 'redux-saga/effects';
    import axios from 'axios';
    import AsyncStorage from '@react-native-async-storage/async-storage';

    function* likePost(action) {
      try {
        const token = yield AsyncStorage.getItem('tokenstore');
        const result = yield call(likePostAPI, action.data, token);
        // console.log("result:",result);
        yield put({
          type: LIKE_POST_SUCCESS,
          data: result.data,
        });
      } catch (err) {
        console.error(err);
      }
    }

    function likePostAPI(data, token) {
      return axios.patch(
        `/post/${data}/like`,
        {},
        {
          headers: {Authorization: `Bearer ${token}`},
        },
      );
    }


    function addPostAPI(action, token) {
      return axios.post('/post', action, {
        headers: {Authorization: `Bearer ${token}`},
      });
    }

    function* addPost(action) {
      try {
        const token = yield AsyncStorage.getItem('tokenstore');
        const result = yield call(addPostAPI, action, token);
        yield put({
          type: ADD_POST_SUCCESS,
          data: result.data,
        });
      } catch (err) {
        console.error(err);
      }
    }



    function* watchLikePost() {
      yield takeLatest(LIKE_POST_REQUEST, likePost);
    }

    function* watchAddPost() {
      yield takeLatest(ADD_POST_REQUEST, addPost);
    }



    export default function* postSaga() {
      yield all([

        fork(watchLikePost),
        fork(watchAddPost),
      ]);
    }

(佐贺/index.js)

    import { all, fork } from 'redux-saga/effects';
    import axios from 'axios';

    import postSaga from './post';
    import userSaga from './user';


    axios.defaults.baseURL = 'http://10.0.2.2:3065';

    export default function* rootSaga() {
      yield all([
        fork(postSaga),
        fork(userSaga),
      ]);
    }

共有1个答案

上官树
2023-03-14

您可以创建一个新的axios实例并使用它,而不是直接使用axios。这样,您就可以拦截每个请求,并将JWT令牌添加到请求标头中。

定制axios。js

import axios from 'axios';

const AxiosInstance = axios.create({
  // A good thing is to set your baseURL here
  baseURL: 'https://your-api.com',
});

AxiosInstance.interceptors.request.use(async (cfg) => {
  // Get your token from the storage
  const token = await AsyncStorage.getItem('tokenstore');

  // If the token exists, attach it to the current request's Authorization header
  if (token) {
    cfg.headers.Authorization = token;
  }

  return cfg;
});

export default AxiosInstance;

然后把它用在你的传奇里

(saga/post.js)

import axiosInstace from '../custom-axios.js'

...
function addPostAPI(action, token) {
  // Now when using axiosInstace, you don't have to add the token to your headers
  // because it will handle it internally for every request made with this instance
  return axiosInstace.post('/post', action);
}
...
 类似资料: