【问题标题】:Passing props to router component in react-router v4 [duplicate]在react-router v4中将道具传递给路由器组件[重复]
【发布时间】:2018-06-17 05:45:37
【问题描述】:

例如:

import SomeComponent...

<Router>
    <Route path='/' component={SomeComponent} />
</Router>

如何将某些内容传递给SomeComponent,以便我可以通过this.props.xxx 在组件中访问它?

【问题讨论】:

  • 好吧,你在&lt;Route 标签上使用render 属性(而不是component 属性),或者你使用redux 之类的东西并创建一个连接的组件,或者使用一个HOC注入一些应该始终可用的数据,有很多选择;)

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


【解决方案1】:

试试这个:

<Router>
    <Route path='/' component={(props) => 
        (<SomeComponent value={this.state.value} {...props} )/>} />
</Router>

注意,如果您想访问组件中的路由属性(例如组件代码中的 this.props.history 中的匹配、位置或历史记录),则需要传递 ...props


更新:

出于性能原因,在这种情况下使用render 可能会更好,例如:

 <Router>
        <Route path='/' render={(props) => 
            (<SomeComponent value={this.state.value} {...props} )/>} />
    </Router>

根据react docs

当你使用组件(而不是渲染或子组件)时 路由器使用 React.createElement 从 给定的组件。这意味着如果您向 组件属性,您将在每次渲染时创建一个新组件。 这会导致现有组件卸载和新的 组件安装,而不是仅仅更新现有组件。 当使用内联函数进行内联渲染时,使用渲染或 children 道具(下)。

【讨论】:

    猜你喜欢
    • 2019-06-08
    • 2018-05-19
    • 2019-05-01
    • 2017-11-06
    • 1970-01-01
    相关资源
    最近更新 更多