如何将props传递给react-router 4组件?

Vin*_*mes 2 reactjs react-router react-router-v4

我喜欢将我的app入口点用作全局州商店.将信息传递给儿童作为道具.

使用react-router 4,如何将prop数据发送到渲染的组件.以类似的方式:

<Route Path=“/someplace” component={someComponent} extra-prop-data={dataPassedToSomeComponent} />
Run Code Online (Sandbox Code Playgroud)

我已经看到了旧版本的react-router的一些janky变通办法,似乎已被弃用.

在v4中执行此操作的正确方法是什么?

小智 5

您可以将函数传递给渲染道具,而不是将组件直接传递给组件道具.

<Route path="/someplace" render={() => <SomeComponent props={} />} />
Run Code Online (Sandbox Code Playgroud)

你可以在这里阅读更多.

  • 实际上,最好使用`render` prop,因为如果你将一个函数传递给一个路径的`component` prop它会重新创建组件(unmount old和mount new)而不是更新它的props.文档https://reacttraining.com/react-router/web/api/Route/component中也提到了这一点. (3认同)
  • 答案的EDIT部分包含一个非常糟糕的建议.今天花了我几个小时.将lambda作为`component`传递导致`componentWillReceiveProps`没有触发(React 16.2).正如@RobinVenneman所描述的那样,该组件可能会不断重建.我应该读他的评论. (2认同)