【问题标题】:Accessing URL param in react-router render function在 react-router 渲染函数中访问 URL 参数
【发布时间】:2018-11-24 02:22:22
【问题描述】:

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

我想通过 react-router v4 使用 render 方法访问 URL 参数。到目前为止我发现的所有东西都只是像这样传递组件:

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

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

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

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

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

【问题讨论】:

标签: javascript reactjs react-router react-router-v4


【解决方案1】:

你需要将 props 从Route 传递给Child

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

或:

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

【讨论】:

  • 谢谢,这行得通。实际上我之前尝试过,但由于我自己构建了一个自定义 PrivateRoute 组件并且我没有将道具传递给渲染函数,它没有工作。
【解决方案2】:

您可以使用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>
      )}
/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2018-02-28
    • 2018-09-23
    相关资源
    最近更新 更多