[英]Redux-Saga axios api call get request with access_token does not work. Why is that?
这是一个使用 axios、redux 和 redux-sagas 的 React 项目。
尝试从受保护的表中获取所有记录时出现以下异常。 我在 laravel 后端使用 JWT。 登录令牌已在本地存储中正确设置,我猜,它没有正确传递。
TypeError: Cannot read properties of null (reading 'authService')
at getAll (PostService.js:11:1)
at runCallEffect (redux-saga-core.esm.js:524:1)
at runEffect (redux-saga-core.esm.js:1204:1)
at digestEffect (redux-saga-core.esm.js:1271:1)
at next (redux-saga-core.esm.js:1161:1)
at proc (redux-saga-core.esm.js:1108:1)
at redux-saga-core.esm.js:585:1
at immediately (redux-saga-core.esm.js:56:1)
at runForkEffect (redux-saga-core.esm.js:584:1)
at runEffect (redux-saga-core.esm.js:1204:1)
这是我要从表中获取每条记录的页面:
import { useEffect } from "react";
import { getAllPostsAction } from "../../store/posts/slice";
import { useSelector, useDispatch } from "react-redux";
import { makeSelectPosts } from "../../store/posts/selector";
export const PostsPage = () => {
const posts = useSelector(makeSelectPosts);
const dispatch = useDispatch();
useEffect(() => {
dispatch(getAllPostsAction());
}, [dispatch]);
console.log(posts);
return <h1>PostsPage</h1>;
};
传奇:
import { call, put, all, fork, takeEvery } from "redux-saga/effects";
import { postService } from "../../services/PostService";
import { setAllPostsAction } from "./slice";
import { setSinglePostAction } from "./slice";
function* getPosts() {
try {
const response = yield call(postService.getAll);
yield put(setAllPostsAction(response.data));
} catch (err) {
console.error(err);
}
}
function* getPostsSagaWatcher() {
yield takeEvery("posts/getAllPostsAction", getPosts);
}
...
// I forked every watcher from a file down bellow in a file
这就是我使用 axios 获取所有内容的方式:
import { authService } from "./AuthService";
import axios from "axios";
class PostService {
constructor() {
this.authService = authService;
}
async getAll() {
return await axios.get("http://127.0.0.1:8000/api/posts", {
headers: this.authService.getHeaders(),
});
}
...
getHeaders() 看起来像这样:
getHeaders() {
return {
Authorization: `Bearer ${window.localStorage.getItem("loginToken")}`,
};
}
我试图获取表中的每条记录并将其设置为组件挂载上的组件 state(useState 挂钩),这非常有效。 所以问题很可能是我发送传奇的方式。
yield call(postService.getAll);
由于您没有指定this
的值,因此使用undefined
for this
调用postService.getAll
。 因此,当 function 尝试访问this.authService
时,它会抛出错误。
call
有几种替代方法,您可以使用它来指定this
的值。 以下所有内容都将起作用:
yield call([postService, postService.getAll])
// or
yield call([postService, 'getAll'])
// or
yield call({ context: postService, fn: postService.getAll })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.