如何在单独的组件中使用 url 参数

How to use url params in separate component

过去 2 天我一直在学习 React,我在理解 URL 参数方面遇到了困难。

假设我想要一条路线 mysite.com/details/1023。路线定义如下:

<Route path="/details/:id" render={() => <DishDetails />}/>

现在我希望在另一个文件中定义的 DishDetails 对象能够使用 id1023。我怎样才能做到这一点?我找到了关于路由 url 参数的教程,但是 none 解释了如何实现这一点。

这是我的 DishDetails 视图现在的样子:

import React, {Component} from "react";
import "./DishDetails.css";
import {Link} from "react-router-dom";

class DishDetails extends Component {
    constructor(props) {
        super(props);
        this.state = {
            id: /*url param*/,
        };
    }
    render() {
        return this.state.id;
    }
}

export default DishDetails;

我在哪里可以得到 DishDetails 中的 id?我试过:

import React, {Component} from "react";
import "./DishDetails.css";
import {Link} from "react-router-dom";

class DishDetails extends Component {
    constructor(props) {
        super(props);
        this.state = {
            id: match.id,
        };
    }
    render() {
        return this.state.id;
    }
}

但是 match 未定义。

你试过react-router自带的withRouter功能了吗?

import { withRouter } from 'react-router'

class App extends Component {
   .... your stuff
}

export default withRouter(App);

这应该可以让您访问 "match" 道具

通过组件道具将您的组件传递给 Route

<Route path="/details/:id" component={DishDetails} />

如果你这样做了 match 在道具中可用。

如果您必须保持渲染路线的方式,您可以手动将渲染道具传递给您的组件:

<Route path="/details/:id" render={(props) => <DishDetails {...props} />}/>

您可以找到 react-router here 的完整文档。

<Route render> prop receives the router props:

  • match
  • location
  • history

您需要向 <DishDetails> 组件提供该道具,并使用 match.params.id 从您的 path="/details/:id"

中检索 id
const DishDetails = props => <div>Details Id: {props.match.params.id}</div>;

<Route path="/details/:id" render={props => <DishDetails {...props} />} />

这是您示例中的路线道具

{
    match: { path: '/details/:id', url: '/details/1', isExact: true, params: { id: '1' } },
    location: { pathname: '/details/1', search: '', hash: '' },
    history: { length: 3, action: 'POP', location: { pathname: '/details/1', search: '', hash: '' } }
}

There are 3 ways to render something with a <Route>:

  • <Route component>
  • <Route render>
  • <Route children>

阅读更多here