如何使动态React路由器保持静态?

时间:2018-04-25 11:39:56

标签: reactjs react-router react-router-v4

React路由器曾经是静态的,但在版本4中它变得动态。这有许多优点,但在某些情况下,您宁可让React组件独立于路由器。例如,如果您要升级到React Router v4并且不想进行太多更改,或者为了可重用性而希望保持组件清除任何路由器功能。

你是怎么做到的?

1 个答案:

答案 0 :(得分:0)

这是使组件摆脱路由器功能的简单方法。

import React from "react";
import { BrowserRouter as Router, Switch, Route, Link} from "react-router-dom";

const App = () => (
  <Router>
    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/items" component={ItemsRouter} />
    </Switch>
  </Router>
);

const ItemsRouter = (props) => {
  if (props.match.isExact)
    return <ItemsList/>

  return (
    <Route exact path={`${props.match.url}/:itemId`} component={Item} />
  );
};

const Home = () => (
  <div>
    <h2>Home page</h2>
    <Link to="/items">Check out the items</Link>
  </div>
);

const ItemsList = () => (
  <div>
    <h2>List of items</h2>
    <ul>
      <ol><Link to="/items/item1">Item 1</Link></ol>
      <ol><Link to="/items/item2">Item 2</Link></ol>
    </ul>
  </div>
);

const Item = ({match}) => {
  let itemName;

  switch (match.params.itemId) {
    case 'item1':
      itemName = 'Item 1';
      break;
    case 'item2':
      itemName = 'Item 2';
      break;
    default:
      itemName = 'Unknown item';
  }

  return <h2>Details for {`${itemName}`}</h2>
}

export default App;