【发布时间】: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