【问题标题】:Converting private Route with props from react-router v5 to react-router v6将带有 props 的私有路由从 react-router v5 转换为 react-router v6
【发布时间】:2021-12-27 11:35:22
【问题描述】:

我在react-router v5有一个路线列表

const agrRouterConfig = [
  {
    path: '/',
    component: Agreements,
    exact: true,
  },
  {
    path: '/agreements/:id',
    component: AgreementPdfPage,
  },
];

export default agrRouterConfig;

我通过这样的自定义路由传递它们,但重要的是我有重要的状态作为道具传递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 中实现这一点?我浏览了文档,方法非常不同,我找不到翻译代码的方法。

【问题讨论】:

    标签: reactjs react-router react-router-dom


    【解决方案1】:

    回答。

    来自 react-router v6 的useRoutes() 接受 router[] 对象的参数。

    在我的具体例子中:

    // 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}/> ,
      },
    

    【讨论】:

      猜你喜欢
      • 2022-06-17
      • 2022-01-17
      • 2022-07-30
      • 2018-10-14
      • 1970-01-01
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      • 2021-11-03
      相关资源
      最近更新 更多