如何在路线外访问比赛?

时间:2020-01-21 22:05:15

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

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

那么有没有类似的设计模式可以让我将所有路径逻辑保留在App中,并且仅根据参数将prop传递给子组件,而不使用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>
    );
  }
}

2 个答案:

答案 0 :(得分:1)

<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}  />
      )}
    />

答案 1 :(得分:0)

尝试使用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);