在 react-router 渲染函数中访问 URL 参数

Accessing URL param in react-router render function

这是一个简单的问题,但到目前为止我还没有找到解决方案:

我想使用 render 方法通过 react-router v4 访问 URL 参数。到目前为止我发现的一切都只是通过这样的组件:

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

但是我想像这样使用渲染方法:

<Route path="/:id" render={() => (<Wrapper> <Child /> </Wrapper>)} />

但是,当我尝试在 Child 组件中使用 props.match.params.id 访问 id 参数时,match 属性未定义。

知道如何使用渲染函数并仍然访问 url 参数吗?

您需要将道具从 Route 传递给 Child:

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

或:

<Route path="/:id" render={(props) => (<Wrapper> <Child id={props.match.params.id} /> </Wrapper>)} />

您可以使用 location.search 在 URL 中获取该查询字符串,并从 location.pathname

获取路径
<Route
      path="/about"
      render={({ location, history }) => (
           <div>
                 <p>We are at: {location.pathname}</p>
                 <p>Query string is: {location.search}</p>
           </div>
      )}
/>