我有一个在我的 App.js 文件中使用的 useEffect 挂钩。它将数据放入我需要在我的应用程序中使用的 redux 存储中。但它在 useEffect 运行之前呈现,因此数据未定义。然后 useEffect 正确运行。我需要在渲染任何内容之前运行 useEffect。我怎么能那样做?或者我应该使用什么其他解决方案?我曾尝试完全删除 useEffect 并只运行该操作,但这会导致它无休止地运行。这是我的代码:
function App() {
const app = useSelector(state => state.app);
const auth = useSelector(state => state.auth);
const dispatch = useDispatch();
useEffect(() => {
dispatch(authActions.checkUser());
}, [dispatch]);
console.log(auth.user); //undefined
return (
<ThemeProvider theme={!app.theme ? darkTheme : theme}>
<CssBaseline />
<React.Fragment>
{/* TODO: Display drawer only when logged in */}
{/* <Drawer></Drawer> */}
<Switch>
<Route exact path="/" component={Login} />
<Route exact path="/dashboard">
<Dashboard user={auth.user} /> //auth.user is undefined when this gets rendered
</Route>
<Route exact path="/register" component={Register} />
</Switch>
</React.Fragment>
</ThemeProvider>
);
}
export const checkUser = () => async dispatch => {
let token = localStorage.getItem("auth-token");
if (token === null) {
localStorage.setItem("auth-token", "");
token = "";
}
const tokenRes = await Axios.post("http://localhost:5000/users/tokenIsValid", null, {
headers: { "x-auth-token": token }
});
if (tokenRes.data) {
const userRes = await Axios.get("http://localhost:5000/users/", {
headers: { "x-auth-token": token }
});
dispatch({
type: CHECK_USER,
token,
user: userRes.data
});
}
};
慕运维8079593
慕姐4208626
相关分类