如果用户单击浏览器上的“后退按钮”,我尝试不再调用loadUserPosts()
函数。我认为这是因为isLogged
useState在单击后退按钮时发生了变化。
只有当用户登录时,loadUserPosts
函数才在useEffect
中,因此我有以下代码:
在Posts.js组件我有这个:
import { useState, useEffect } from "react";
import { AuthUseContext } from '../context/AuthContext';
import Axios from 'axios';
function Posts() {
const [posts, setPosts] = useState([]);
const { isLogged, setIsLogged, userData, setUserData } = AuthUseContext();
useEffect(() => {
if(isLogged) {
loadUserPosts();
}
}, [isLogged]);
// my API request to load all user posts
function loadUserPosts()
{
Axios.post('/posts/load', {
user: userData.id
}).then((response) => {
if(response.data.status === "success")
{
setPosts(response.data.posts);
}
}).catch((error) => {
console.log("Something went wrong.. We are investigating.");
})
}
return (
<>
{posts.map((p) => {
<div className="post" key={p.id}>
<div className="post-user">
{p.username}
</div>
<div className="post-text">
{p.message}
</div>
</div>
})}
</>
)
}
export default Posts
如果删除依赖项[isLogged]
,则isLogged将为false
,因为App.js中API请求的结果尚未发送。
在app.js中,我有一个API请求后端检查用户是否登录(使用NodeJs/Express作为后端,使用cookie会话作为中间件)。
import { useEffect } from 'react'
import { Route, Routes } from 'react-router-dom'
import './css/style.css'
import Sidebar from './pages/Sidebar'
import Posts from './pages/Posts'
import { AuthUseContext } from './context/AuthContext';
import Axios from 'axios'
function App() {
const { isLogged, setIsLogged, userData, setUserData } = AuthUseContext();
useEffect(() => {
Axios.post('/checkuser', {
userStatus: isLogged,
userData: userData
}).then((response) => {
setIsLogged(response.data.status); // true / false
setUserData(response.data.userdata); // { id: ..., name: ..., ...etc...}
}).catch(function (error) {
console.log("Something went wrong.. We are investigating.");
});
// eslint-disable-next-line
}, [isLogged])
return (
<>
<Sidebar />
<div className="content">
<Routes>
<Route path="/" element={<Posts />} />
<Route path="*" element={ <h1>Not found (404)</h1> } />
</Routes>
</div>
</>
);
}
export default App;
有人能帮助我吗?或者我应该如何构造我的组件?
2条答案
按热度按时间zhte4eai1#
使用react query,它处理网络缓存,因此不会再次发出请求
mw3dktmi2#
由于您正在使用useEffect,并且正在调用API。因此,不可能停止API的调用。根据您的代码,一旦您访问屏幕,将首次调用API。
作为参考,请查看此帖子关于useEffect https://reactjs.org/docs/hooks-effect.html