[英]Converting private Route with props from react-router v5 to react-router v6
我有react-router v5
中的路线列表
const agrRouterConfig = [
{
path: '/',
component: Agreements,
exact: true,
},
{
path: '/agreements/:id',
component: AgreementPdfPage,
},
];
export default agrRouterConfig;
我通过这样的自定义路线传递它们,但重要的是我有重要的 state 作为道具setShowAgreement
传递:
const RouteWithSubRoutes = (route: any) => {
return (
<Route
path={route.path}
exact={route.exact}
render={(props) => (
<route.component
{...props}
routes={route.routes}
setShowAgreement={route.setShowAgreement}
/>
)}
/>
);
};
在应用程序内部:
const Routes = () => {
const [showAgreement, setShowAgreement] = useState(false);
///// some code
if (showAgreement) {
return (
<Switch>
{agrRouterConfig.map((route, i) => (
<RouteWithSubRoutes key={i} {...route} setShowAgreement={setShowAgreement} />
))}
</Switch>
);
}
///// some code
);
};
对我来说重要的是将setShowAgreement
作为道具传递给路由。 如何在react-router v6
中实现这一点? 我浏览了文档,方法非常不同,我找不到翻译我的代码的方法。
回答。
useRoutes()
接受router[]
object。
在我的特定示例中:
// app.tsx
const App = () => {
let element = useRoutes(routerConfig(setShowAgreement));
return <>element </>
}
在 routerObjc.tsx 里面
//routerObjc.tsx
const routerConfig = (setShowAgreement?: ()=>void ) => [
{
path: '/documents',
element: <Documents setShowAgreemnt={setShowAgreemnt}/>/>
},
{
path: '/profile',
element: <Profile setShowAgreemnt={setShowAgreemnt}/> ,
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.