如何让 withRouter 将匹配参数传递给组件?

How to get withRouter to pass match params to component?

我想在我的应用程序的导航中访问匹配参数,我正在使用 reactreact-router-dom。这是我制作的简单示例的代码片段,正如您在主题组件上看到的那样,我在组件级别获得了正确的匹配,但在导航栏中却没有,我确实在 location 道具中获得了正确的 url 路径,所以我不确定我这样做是否正确。

This would be the working snippet,因为我无法将 react-router-dom 添加到堆栈溢出代码段。

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

const BasicExample = (props) =>
  <Router>
    <div>
      <Nav/>
      <hr />

      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/topics" component={Topics} />
    </div>
  </Router>;


const About = () => (
  <div>
    <h2>About</h2>
  </div>
);

const Home = () => (
  <div>
    <h2>Home</h2>
  </div>
);

const Navigation = (props) => (
  <ul>
    <li>
      <Link to="/">Home</Link>
    </li>
    <li>
      <Link to="/about">About</Link>
    </li>
    <li>
      <Link to="/topics">Topics</Link>
    </li>
    <li>{`match prop -> ${JSON.stringify(props.match)}`}</li>
    <li>{`location prop -> ${JSON.stringify(props.location)}`}</li>
  </ul>
);

const Nav =  withRouter(Navigation);

const Topic = ({ match, location }) => (
  <div>
    <h3>{match.params.topicId}</h3>
    <li>{`match prop -> ${JSON.stringify(match)}`}</li>
    <li>{`location prop -> ${JSON.stringify(location)}`}</li>
  </div>
);

const Topics = ({ match, location, history }) => (
  <div>
    <h2>Topics</h2>
    <li>{`match prop -> ${JSON.stringify(match)}`}</li>
    <li>{`location prop -> ${JSON.stringify(location)}`}</li>
    <ul>
      <li>
        <Link to={`${match.url}/rendering`}>
          Rendering with React
        </Link>
      </li>
      <li>
        <Link to={`${match.url}/components`}>
          Components
        </Link>
      </li>
      <li>
        <Link to={`${match.url}/props-v-state`}>
          Props v. State
        </Link>
      </li>
    </ul>

    <Route path={`${match.url}/:topicId`} component={Topic} />
    <Route
      exact
      path={match.url}
      render={() => <h3>Please select a topic.</h3>}
    />
  </div>
);


ReactDOM.render(<BasicExample />, document.getElementById("root"));
<body>
  <div id="root"></div>
  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
</body>

为了检测 <Nav> 中的 :topicId 使用从 react-router 导入的 matchPath:

import { matchPath } from 'react-router'

matchPath(location.pathname, { 
  path:'/topics/:topicId',
  exact: true,
  strict: false
}})

这现在有点过时了。可以通过 react-router-dom 通过简单地执行以下操作来实现:

import { withRouter } from 'react-router-dom';

console.log(props.match.params);

不要忘记将组件包裹在 withRouter

export default withRouter(YourComponent);

props.match.params 将 return 一个包含所有参数的对象。