所以我想调用从auth.js
导入的loadUser
函数,但有些原因是auth.js中的loadUser
函数没有被调用。我试图在App.js的useEffect()
和auth.js
的loadUser()
中控制台日志,我从useEffect((得到了反馈,但从未从loadUser()
得到任何反馈,在我看来,这可能是因为函数没有正确导出或导入,但我似乎找不到问题出在哪里。
App.js
import { loadUser } from "./actions/auth";
import setAuthToken from "./utils/setauthtoken";
import "./App.css";
const App = () => {
useEffect(() => {
if (localStorage.token) {
setAuthToken(localStorage.token);
store.dispatch(loadUser);
console.log("use efect app.js");
}
});
auth.js
import axios from "axios";
import setAuthToken from "../utils/setauthtoken";
import { setAlert } from "./alert";
import {
REGISTER_SUCCESS,
REGISTER_FAIL,
USER_LOADED,
AUTH_ERROR,
} from "./types";
//load user
export const loadUser = () => async (dispatch) => {
console.log("from loaduser auth.js");
if (localStorage.token) {
setAuthToken(localStorage.token);
}
try {
const res = await axios.get("/api/auth");
console.log("inside auth.js get auth route");
dispatch({
type: USER_LOADED,
payload: res.data,
});
} catch (err) {
dispatch({
type: AUTH_ERROR,
});
}
};
想明白了,App.js中的store.dispatch(loadUser)
应为store.dispatch(loadUser())