简体   繁体   English

如何在反应路由器 dom v4 的组件中获取参数?

[英]How to get params in component in react router dom v4?

I have this code:我有这个代码:

<BrowserRouter>
   <Route  path="/(:filter)?" component={App} />
</BrowserRouter>

the filter param or '' on the root is suppose to be on App components' props base on the previous react router versions?根上的过滤器参数或 '' 假设基于以前的反应路由器版本在应用程序组件的道具上?

This is my code on my App:这是我在我的应用程序上的代码:

const App = ({params}) => {
    return ( // destructure params on props
      <div>
        <AddTodo />
        <VisibleTodoList 
            filter={params.filter || 'all'} // i want to git filter param or assign 'all' on root 
        />
        <Footer />
      </div>
    );
}

I logged this.props.match.params on console but it has none?我在控制台上记录了 this.props.match.params 但它没有? help?帮助?

I assume you are following the Redux tutorial on Egghead.io , as your example code seems to use what is defined in that video series.我假设您正在关注Egghead.io 上Redux 教程,因为您的示例代码似乎使用了该视频系列中定义的内容。 I also got stuck on this part trying to integrate React Router v4, but eventually found a working solution not far from what you have tried.我也在尝试集成 React Router v4 的这部分卡住了,但最终找到了一个与您尝试的方法相距不远的可行解决方案。

⚠️ NOTE: one thing I would check here is that you are using the current version of react-router-dom ( 4.1.1 at the time of this writing). ⚠️ 注意:我要在这里检查的一件事是您使用的是当前版本的react-router-dom (撰写本文时为4.1.1 )。 I had some issues with optional filters in the params on some of the alpha and beta versions of v4.我在 v4 的某些 alpha 和 beta 版本的参数中遇到了一些可选过滤器问题。

First, some of the answers here are incorrect, and you indeed can use optional params in React Router v4 without the need for regular expressions, multiple paths, archaic syntax, or using the <Switch> component.首先,这里的一些答案是不正确的,您确实可以在 React Router v4 中使用可选参数,而无需正则表达式、多路径、古老的语法或使用<Switch>组件。

<BrowserRouter>
  <Route  path="/:filter?" component={App} />
</BrowserRouter>

Second, as others have noted, React Router v4 no longer exposes params on route handler components, but instead gives us a match prop to use.其次,正如其他人所指出的,React Router v4 不再在路由处理程序组件上公开params ,而是为我们提供了一个match属性供我们使用。

const App = ({ match }) => {
    return (
      <div>
        <AddTodo />
        <VisibleTodoList filter={match.params.filter || 'all'} />
        <Footer />
      </div>
    )
}

From here, there are two ways to keep your content in sync with the current route: using mapStateToProps or using the HoC withRouter , both solutions are already talked about in the Egghead series so I won't recapitulate them here.从这里开始,有两种方法可以使您的内容与当前路由保持同步:使用mapStateToProps或使用 HoC withRouter ,这两种解决方案都已在 Egghead 系列中讨论过,因此我不会在这里重述它们。

If you are still having trouble, I urge you to check out my repository of the completed application from that series.如果您仍然遇到问题,我强烈建议您查看我的该系列已完成应用程序的存储库。

Both of which seem to work fine (I just tested both of them).两者似乎都可以正常工作(我刚刚测试了它们)。

React Router v4 does not accept a regex for the path. React Router v4 不接受路径的正则表达式。 You won't find regular expressions covered anywhere in the documentation.您不会在文档中的任何地方找到正则表达式。 Instead of a regex you can just create multiple routes inside the <Switch> component and the first one that matches will be rendered:您可以在<Switch>组件内创建多个路由,而不是正则表达式,并且将呈现第一个匹配的路由:

<BrowserRouter>
  <Switch>
    <Route  path="/" component={App} />
    <Route  path="/:filter" component={App} />
  </Switch>
</BrowserRouter>

You also have a bug in your App component.您的 App 组件中也有一个错误。 You get the params via the match property, not the params property (not tested, but this should be closer to what you want):您通过 match 属性获取参数,而不是 params 属性(未测试,但这应该更接近您想要的):

const App = ({match}) => {
    return ( 
      <div>
        <AddTodo />
        <VisibleTodoList 
            filter={match.params.filter || 'all'} 
        />
        <Footer />
      </div>
    );
}

All of the above is covered in the React Router V4 docs on ambiguous matches以上所有内容都包含在关于模糊匹配React Router V4 文档中

From the react-router documentation , props.match.params is where your parameteres are stored.react-router文档中props.match.params是存储参数的地方。

So to access the filter name, try this所以要访问过滤器名称,试试这个

const App = ({match}) => {
    ...
    <VisibleTodoList 
        filter={match.params.filter || 'all'}
    />
    ...
}

I know the question is about v4, but if sm looks for v5, we can use the useParams hook.我知道问题是关于 v4 的,但是如果 sm 寻找 v5,我们可以使用useParams钩子。

// /:filter
const {filter} = useParams();

To get the params in the path URL获取路径 URL 中的参数

//to your route component  
<Route path={`${match.url}/upload/:title`} component={FileUpload}/> 
=====
//Parent component
<Link to={`${match.url}/upload/css`}>  
=====
//Child component  
const {params: {title}} = this.props.match;
console.log(title);

result = css

I do not know why react router cannot detect my filter even though it's working properly, I resolved this problem by using location.pathname since it does the work for me.我不知道为什么 react router 无法检测到我的过滤器,即使它工作正常,我通过使用 location.pathname 解决了这个问题,因为它为我工作。 I think react router cannot detect my filter param because of regexp, I expected that so I put ||我认为由于正则表达式,react router 无法检测到我的过滤器参数,我预料到了,所以我把 || to use all on root, but unfortunately for me I it cannot detect so I used location.pathname .在 root 上使用 all,但不幸的是我无法检测到,所以我使用了 location.pathname 。 I would appreciate suggestions on this since I am not sure with my path configuration on regexp.我很感激这方面的建议,因为我不确定我在 regexp 上的路径配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM