简体   繁体   English

我如何使用 React lazy to Router

[英]How can I use React lazy to Router

I want to pass the props from router to component我想将道具从路由器传递到组件

function TestComponent({myProps: string}): {
  console.log(myProps)
  useEffect(...)
  return (
    <>...</>  
  )
};

My router use react lazy like this我的路由器像这样懒惰地使用反应

import React, { lazy } from 'react';
export const routes = [
  ...
  {
    path: '/test/testComponent',
    exact: true,
    component: lazy(
      () => import('pages/test/TestComponent/index'),
    ),
  },
  ...
];

I find this way我找到了这条路

{
  path: '/test/testComponent',
  component(): React.ReactElement {
  return <DeviceAssignmentLog myProps=''hello />;
  },
},

but I have to use lazy with that但我必须用懒惰的

how can I solve...我该如何解决...

You can just assign the lazy loaded component to a variable and then pass the required props into the config object so the inside the router file you do something like this您可以将延迟加载的组件分配给一个变量,然后将所需的道具传递到配置 object 中,这样您就可以在路由器文件中执行类似这样的操作

import React, { lazy } from 'react';

const LazyLoadedComponent = lazy(()=> import('/path-to-component'))

const routes = [
  ...
  {
    path: '/test/testComponent',
    component:()=>(<LazyLoadedComponent myProps='required-prop-value'  />),
  },
  ...
]
import React, { Suspense, lazy } from 'react'
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'

const Home = lazy(() => import('./pages/Home'))

const App = () => {
  return (
    <Router>
      <Suspense>
        <Routes>
          <Route path="/" element={<Home myProps={'hello'} />} />
          // Your routes more here
        </Routes>
      </Suspense>
    </Router>
  )
}

export default App

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM