【问题标题】:How to pass props to react-router 4 components?如何将道具传递给 react-router 4 组件?
【发布时间】:2018-04-25 13:01:37
【问题描述】:

我喜欢将我的应用入口点用作全局状态存储。将信息作为道具传递给孩子。

使用 react-router 4,如何将 prop 数据发送到渲染组件。与此类似:

<Route Path=“/someplace” component={someComponent} extra-prop-data={dataPassedToSomeComponent} />

我已经看到一些旧版本的 react-router 的变通方法,似乎已被弃用。

在 v4 中这样做的正确方法是什么?

【问题讨论】:

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


【解决方案1】:

从技术上讲,有两种方法可以做到这一点。

第一个(不是最有效的)是将一个内联函数传递给组件prop:

<Route 
  path=“/someplace” 
  component={(props) => (
    <SomeComponent {...props} extra-prop-data={ dataPassedToSomeComponent } />
  ) />

第二个是最好的解决方案。为了防止像第一个示例那样在每次渲染时都创建一个新组件,我们将相同的内联函数传递给了 render prop:

<Route 
  path=“/someplace” 
  render={(props) => (
    <SomeComponent {...props} extra-prop-data={ dataPassedToSomeComponent } />
  ) />

【讨论】:

    【解决方案2】:

    您可以将一个函数传递给render prop,而不是将组件直接传递给组件prop。

    <Route path="/someplace" render={() => <SomeComponent props={} />} />
    

    您可以阅读更多here

    【讨论】:

    • 是的!我现在记得在另一个项目中这样做了。我回家后会试一试。谢谢??
    • @Raj 考虑添加对docs的引用
    • 添加了参考!
    • 实际上,最好使用render 属性,因为如果您将函数传递给路由的component 属性,它将重新创建组件(卸载旧组件并安装新组件)而不是更新其属性。文档reacttraining.com/react-router/web/api/Route/component 中也提到了这一点
    • 答案的编辑部分包含一个非常糟糕的建议。今天跟踪它花了我几个小时。将 lambda 传递为 component 导致 componentWillReceiveProps 未触发(React 16.2)。正如@RobinVenneman 所描述的那样,可能会不断地重新创建该组件。我应该看看他的评论。
    【解决方案3】:

    并且要添加到上述答案,如果您希望组件可以访问路由属性,则需要包含这些属性。现在,当路由器激活“SomeComponent”时,该组件将获取所有路由道具以及额外的参数 - 在本例中为“参数”。

    <Route path='/someplace' component={(props) => <SomeComponent param="yo" {...props}/>} />
    

    【讨论】:

    • 在此之前,请参阅 RobinVenneman 和我的 cmets 以接受已接受的答案。
    猜你喜欢
    • 2018-07-17
    • 2015-09-21
    • 2018-05-19
    • 2018-12-14
    • 2019-05-08
    • 1970-01-01
    • 2015-03-08
    • 2021-12-21
    • 1970-01-01
    相关资源
    最近更新 更多