React Router V4 - 无法在 props 中获取 URL 参数

React Router V4 - Can't get URL params in props

我正在尝试创建简单的 React-Redux-Router V4 应用程序。到我的组件之一的路由使用了 url 参数。在我的 Route 组件中,我一直在传递 render 属性,这是一个 returns 组件的匿名函数。像这样:

<Route key="post" path="/post/:id" render={() => <Post/>} />

我使用这个道具而不是 component 道具:

<Route key="post" path="/post/:id" component={Post} />

因为我无法使用 component 道具将道具放入渲染的组件中。问题是,使用 component 道具,您可以使用 props.match.params.name,它将包含我需要的确切参数。这在使用 render 组件时不可用。

我可以用window.location.href但是感觉很脏

谢谢!

matchlocationhistory 属性已传递到您的 render 函数中。

示例:

<Route key="post" path="/post/:id" render={({ match }) => <Post name={match.params.name}/>} />

文档:https://reacttraining.com/react-router/web/api/Route/Route-props

你需要先导入这个

import { withRouter } from 'react-router-dom';

最后像这样导出组件。 'User' 是一个 class 组件名称

export default (withRouter(User));

现在,如果您打印该值,您将得到响应。

constructor(props) {
        super(props);
        console.log('Props', this.props);
    }

快乐编码