如何使用路由器将匹配参数传递给组件?

时间:2017-08-17 12:14:53

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

我想在我的应用导航中访问匹配参数,我正在使用reactreact-router-dom。这是一个代码剪切了我做的简单示例,你可以在主题组件上看到我在组件级别得到正确匹配但不在导航栏中,我在位置道具中得到正确的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>

2 个答案:

答案 0 :(得分:5)

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

import { matchPath } from 'react-router'

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

答案 1 :(得分:0)

这有点过时了。只需执行以下操作即可使用react-router-dom来实现:

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

console.log(props.match.params);

不要忘记将组件包装在withRouter

export default withRouter(YourComponent);

props.match.params将返回带有所有参数的对象。