如何访问路由之外的匹配项?

How to access match outside of Route?

完成我在下面代码中尝试的任务的最佳方法是什么?应用程序无法访问其中定义的路由 match.params,但我想根据 url 参数将部分状态传递给子组件。我不能使用像 useRouteMatch() 这样的钩子,因为 App 是一个有状态的 class 组件。我想我可以使用 Route render 方法来做到这一点,但看起来 React Router 文档说该方法已被弃用。

那么有没有类似这样的设计模式,让我把所有的路由逻辑都保留在App中,只根据params将props传递给子组件,而不使用Route的render方法?

class App extends React.Component {
  state = { things: this.props.things };
  render() {
    return (
      <Switch>
        <Route path='/thing/:thingId'>
          <OneThing thing={this.state.things.find(thing => thing.id === match.params.thingId)} />
        </Route>
        <Route path='/things/:thingTag'>
          <MultipleThings things={this.state.things.filter(thing => thing.tag === match.params.thingTag)} />
        </Route>
      </Switch>
    );
  }
}

尝试使用 withRouter

import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";

// A simple component that shows the pathname of the current location
class OneThing extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  };

  render() {
    const { match, location, history } = this.props;

    return <div>You are now at {location.pathname}</div>;
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
export default withRouter(ShowTheLocation);

<Route render>

    <Route path='/thing/:thingId' 
        render={(route) => <OneThing thing={route.match.params.thingId}  />} />


使用 <Route children> 版本 5.1

<Route
       path='/thing/:thingId'
      children={({ match }) => (
        <OneThing thing={match.params.thingId}  />
      )}
    />