Reactjs 在加载页面之前加载预请求资源的最佳实践
假设我有一个包含以下页面的应用程序存储 /stores/:store\u id/ /商店/:商店id/产品/ /门店/:门店id/产品/:产品id 用户可以直接访问/stores/:store\u id/产品/:produc\u id Hoever,在装载仓库和产品之前 我需要做一些请求Reactjs 在加载页面之前加载预请求资源的最佳实践,reactjs,Reactjs,假设我有一个包含以下页面的应用程序存储 /stores/:store\u id/ /商店/:商店id/产品/ /门店/:门店id/产品/:产品id 用户可以直接访问/stores/:store\u id/产品/:produc\u id Hoever,在装载仓库和产品之前 我需要做一些请求 /验证者 /loadUserInfo 但是,如果用户已经验证,我不想一次又一次地调用,/validateUser,/loadUserInfo 因为我的申请表有50页。 我不想在每一页上写上50次以上的检查,
- /验证者
- /loadUserInfo
是否在加载任何页面之前先运行检查?当然有,您是否使用路由库?即使您不是,您也可以创建高阶函数(HOC)来实现您的目标
import React, { useEffect, useState } from "react";
const withAuthentication = (Component) => (props) => {
const [auth, setAuth] = useState(false);
const [isLoading, setLoading] = useState(true);
useEffect(() => {
const checkAuthentication = () => {
setTimeout(() => {
setAuth(true);
setLoading(false);
}, 2000);
};
checkAuthentication();
}, []);
if (isLoading) {
return <div>Loading...</div>;
}
return (
<div>
{auth ? <Component {...props} /> : <div>No permission component</div>}
</div>
);
};
const Div = (props) => {
console.log(props);
return <div>Test</div>;
};
export default function App() {
const Comp = withAuthentication(Div);
return (
<div>
<Comp match={{ params: ["foo"] }} />
</div>
);
}
import React,{useffect,useState}来自“React”;
const with authentication=(组件)=>(道具)=>{
const[auth,setAuth]=useState(false);
const[isLoading,setLoading]=useState(true);
useffect(()=>{
const checkAuthentication=()=>{
设置超时(()=>{
setAuth(真);
设置加载(假);
}, 2000);
};
checkAuthentication();
}, []);
如果(孤岛加载){
返回装载。。。;
}
返回(
{auth?:没有权限组件}
);
};
常量Div=(道具)=>{
控制台日志(道具);
回归试验;
};
导出默认函数App(){
const Comp=withAuthentication(Div);
返回(
);
}
这只是一个快速的草稿,可能有很多错误。在此之后,您可以将所有组件包装到这个HOC中,它们将是安全的cool~但是,当我使用您的方法时。。。受保护的组件将不再具有对props.match.params的访问权限…您可以通过组件传递这些props,我将编辑答案