如何在不首先返回初始值 null 的情况下仅从 useeffect 获取更新值?
How can I get the updated value only from a useeffect without it first returning the initial value null?
我正在创建一个验证挂钩,用于检查用户是否通过服务器的身份验证以及 returns 值。
export function useAuth() {
const [isAuthenticated, setIsAuthenticated] = useState(null);
useEffect(() => {
let mounted = true;
axios({
method: 'GET',
url: 'http://localhost:8000/api/still-authenticated/',
headers: {
'Content-type': 'application/json',
},
withCredentials: true,
})
.then((res) => {
if (mounted) {
setIsAuthenticated(res.data.isAuthenticated);
}
});
return () => mounted = false;
},[setIsAuthenticated])
return isAuthenticated;
}
在测试函数时我注意到它首先 returns null 然后用 axios fetch 更新值 true/false.
现在我的问题是:有没有办法让我在不使用 useEffect 的情况下只接收更新后的值(我试过 useLayoutEffect 但它也不起作用)?
我认为评论希望您执行以下操作。我同意,在从 API.
获取数据时使用加载程序
export function useAuth() {
const [isAuthenticated, setIsAuthenticated] = useState(null);
useEffect(() => {
let mounted = true;
axios({
method: 'GET',
url: 'http://localhost:8000/api/still-authenticated/',
headers: {
'Content-type': 'application/json',
},
withCredentials: true,
})
.then((res) => {
if (mounted) {
setIsAuthenticated(res.data.isAuthenticated);
}
});
return () => mounted = false;
},[isAuthenticated])
return {isAuthenticated ? isAuthenticated : {/*INSERT LOADER HERE OR TEXT*/}};
}
我正在创建一个验证挂钩,用于检查用户是否通过服务器的身份验证以及 returns 值。
export function useAuth() {
const [isAuthenticated, setIsAuthenticated] = useState(null);
useEffect(() => {
let mounted = true;
axios({
method: 'GET',
url: 'http://localhost:8000/api/still-authenticated/',
headers: {
'Content-type': 'application/json',
},
withCredentials: true,
})
.then((res) => {
if (mounted) {
setIsAuthenticated(res.data.isAuthenticated);
}
});
return () => mounted = false;
},[setIsAuthenticated])
return isAuthenticated;
}
在测试函数时我注意到它首先 returns null 然后用 axios fetch 更新值 true/false.
现在我的问题是:有没有办法让我在不使用 useEffect 的情况下只接收更新后的值(我试过 useLayoutEffect 但它也不起作用)?
我认为评论希望您执行以下操作。我同意,在从 API.
获取数据时使用加载程序export function useAuth() {
const [isAuthenticated, setIsAuthenticated] = useState(null);
useEffect(() => {
let mounted = true;
axios({
method: 'GET',
url: 'http://localhost:8000/api/still-authenticated/',
headers: {
'Content-type': 'application/json',
},
withCredentials: true,
})
.then((res) => {
if (mounted) {
setIsAuthenticated(res.data.isAuthenticated);
}
});
return () => mounted = false;
},[isAuthenticated])
return {isAuthenticated ? isAuthenticated : {/*INSERT LOADER HERE OR TEXT*/}};
}