【问题标题】:How can I use asyncstorage without duplication?如何在不重复的情况下使用 asyncstorage?
【发布时间】:2021-07-12 03:17:34
【问题描述】:

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

然后每次我使用 AsyncStorage.getItem 来获取令牌。换句话说,它重叠

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

因为我必须使用 jwt 令牌

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

我需要继续将这样的标头传递给 api。这也是重叠的

我怎样才能在没有冗余的情况下使用它,或者我怎样才能最方便地使用它?

这是我的代码

(传奇/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),
      ]);
    }

【问题讨论】:

    标签: javascript node.js reactjs react-native


    【解决方案1】:

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

    custom-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;
    

    然后在你的 sagas 中使用它

    (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);
    }
    ...
    

    【讨论】:

    • 我更新了我的帖子。但我已经使用基本 url.. 在这种情况下,我该如何添加和应用您的代码?
    • 您还可以将Authorization 标头添加到axios.defaults 属性。看this回答的第2项。
    猜你喜欢
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 2020-10-18
    • 2019-09-06
    • 1970-01-01
    • 2017-08-13
    • 2012-10-23
    相关资源
    最近更新 更多