返回当前处于承诺状态的值



所以这更像是一个javascript问题而不是一个reactjs问题。我在reactjs中创建了一个受保护的路由。在这里,我正在获取'/checkauth' get请求来检查身份验证,它正确地返回响应给我。然而,问题是,因为它是一个异步函数,它需要时间来返回该值,因此我的返回语句被提前执行。这是我遇到问题的代码。

const [auth, setAuth] = useState();
const checkAuthentication = async ()=>{
const res = await fetch('/checkauth', {
method : "GET",
credentials: "include", 
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
});
const data = await res.json();
return res.status===200 ? (data.isAuthenticated) : (false) ;
}
useEffect(async ()=>{
const data = await checkAuthentication();
setAuth(data)
}, []);
return auth ? <Outlet /> : <Navigate to='/signin' />;

这里的验证值总是未定义的,因此它总是导航到签名。

使用三种状态

const [auth, setAuth] = useState("loading");

setAuth(data ? "auth" : "not-auth");

if (auth === "loading")
return <Loading />
else if (auth === "not-auth")
return <Navigate to='/signin' />
else 
return <Outlet />

你可以在获取数据时返回一个加载旋转器,当请求完成时,状态将被更新,<Outlet />组件将被呈现。

顺便说一下:当你将一个async函数传递给useEffect钩子时,它返回一个promise,而useEffect不期望回调函数返回promiseE,相反,它期望回调不返回任何东西(未定义)或返回一个函数(通常是一个清理函数)。

试试这个:

useEffect(() => {
// declare the async data fetching function
const fetchData = async () => {
// get the data from the api
const data = await fetch('https://yourapi.com');
// convert the data to json
const json = await response.json();
// set state with the result
setData(json);
}
// call the function
fetchData()
// make sure to catch any error
.catch(console.error);;
}, [])

  • 更多信息:

React Hook warning for async function in useEffect: useEffect函数必须返回一个cleanup函数或者什么都不返回

最新更新