簡體   English   中英

使用反應路由器通過側邊欄導航動態渲染組件的更簡單方法

[英]Easier way to dynamically render components with sidebar navigation using react router

目前正在通過本教程創建一個帶有反應路由器的側邊欄導航系統https://reacttraining.com/react-router/web/example/sidebar

我計划有多條路線,所以這意味着我必須繼續導入路線並將它們添加到routes數組中。 是否有一種智能/正確的方法來動態加載它們?

我的所有組件都將在我的/Views文件夾中。

應用程序.js

import React, { Component } from 'react';
import SideBar from './components/SideBar/SideBar';
import MainContent from './components/MainContent/MainContent';
import { BrowserRouter as Router,
} from 'react-router-dom';


// Import all components here
import Button from './components/Views/Button/Button';
import Color from './components/Views/Color/Color';
import Card from './components/Views/Card/Card';
import Filter from './components/Views/Filter/Filter';

const routes = [
  {
    path: "/",
    name: 'home',
    exact: true,
    main: () => <h2>Home</h2>
  },
  {
    path: "/button",
    name: 'Button',
    main: () =>  <Button />
  },
  {
    path: "/color",
    name: 'Color',
    main: () =>  <Color />
  },
  {
    path: "/card",
    name: 'Card',
    main: () =>  <Card />
  },
  {
    path: "/filter",
    name: 'Filter',
    main: () =>  <Filter />
  },
];

class App extends Component {
  render() {
    return (
      <Router>
        <div className="ds-container">
          <SideBar routes={routes} />
          <MainContent routes={routes} />
        </div>
      </Router>
    );
  }
}

export default App;

由於您使用的是在內部使用 webpack 的 create-react-app,因此您可以查看require-context 這將幫助您動態導入文件夾中與某個正則表達式匹配的所有文件。 (例如:以 .jsx/.js 結尾)

但是,我建議您不要這樣做:

  1. 您永遠不會知道您目前正在迎合哪些路線。
  2. 它可能會降低您的代碼可讀性。
  3. 您可能還必須導出組件的映射( path中的path )以及組件本身。

為了避免所有這些,您可以簡單地在您的Views組件中創建一個index.js文件,該文件需要您創建的任何新路由組件並返回您在App.js文件中形成的最終數組。

所以本質上, /Views/index.js

// Import all components here
import Button from './components/Views/Button/Button';
import Color from './components/Views/Color/Color';
import Card from './components/Views/Card/Card';
import Filter from './components/Views/Filter/Filter';

const routes = [
  {
    path: "/",
    name: 'home',
    exact: true,
    main: () => <h2>Home</h2>
  },
  {
    path: "/button",
    name: 'Button',
    main: () =>  <Button />
  },
  {
    path: "/color",
    name: 'Color',
    main: () =>  <Color />
  },
  {
    path: "/card",
    name: 'Card',
    main: () =>  <Card />
  },
  {
    path: "/filter",
    name: 'Filter',
    main: () =>  <Filter />
  },
  // add new routes here
];

export default routes;

SideBar.js 中

import routes from 'path/to/views/Views';

//rest of your code to render the routes.

這樣,您將清理 App.js 中的代碼,並且還能夠有效地分離各個組件的關注點。

我希望這是有道理的 :)

根據當前位置,有多種方法可以選擇主要組件。 但是所有這些都需要列出所有可能的路由並導入相應的組件。 您可以使用 動態導入React.lazy來更輕松地進行代碼拆分。

但是您可以避免對側邊欄進行額外配置。 側邊欄可以從全局狀態獲取配置,您的主要組件可以在掛載時更新該狀態( componentDidMountuseEffect(() => {...}, []) ):

const SideBarContext = React.createContext(() => {});

function useSidebar(name) {
  const setSidebarName = useContext(SideBarContext);
  useEffect(() => {
    setSidebarName(name);
    return () => setSidebarName(null);
  }, []);
}

function Home() {
  useSidebar('home');
  return <h2>Home</h2>;
}

function Button() {
  useSidebar('Button');
  return <button>press me</button>;
}

function App() {
  const [name, setName] = useState(null);

  return (
      <Router>
        <div className="ds-container">
          <SideBar name={name} />
          <SideBarContext.Provider value={setName}>
            <Route path="/" exact component={Home}/>
            <Route path="/button" component={Button}/>
          </SideBarContext.Provider>
        </div>
      </Router>
  );
}

所以每個組件都會關心側邊欄的選項,你只需要導入它們並添加Route s。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM