【问题标题】:How to access match outside of Route?如何在路线之外访问比赛?
【发布时间】:2020-01-21 22:05:15
【问题描述】:

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

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

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

【问题讨论】:

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


    【解决方案1】:

    &lt;Route render&gt;

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


    &lt;Route children&gt; 5.1 版

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

    【讨论】:

    • 谢谢,这行得通,但我也想知道是否有办法在没有渲染方法的情况下做到这一点。
    • 你在哪里找到不推荐使用的渲染方法,我找不到?
    • "虽然它们在 5.1 中没有被弃用,但 API 有几个在带有钩子的世界中是不需要的(参见上面的 useParams 中的讨论) . 我们很可能会在未来的版本中弃用这些 API。”来自:reacttraining.com/blog/react-router-v5-1
    • 我已将答案更新为 5.1 版,请查看
    • 太棒了!你这个炸弹!
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2017-01-13
      相关资源
      最近更新 更多