我想为我的应用使用网址路径 . 目前我只是在 app.js
中渲染一个 Main
组件:
render() {
return (
<Main
isLoggedIn={this.state.isLoggedIn}
user={this.state.user}
... />
)
}
(道具是一堆变量和功能)
我尝试使用react-router但我不明白如何向子组件发送道具 .
<Router history={browserHistory} >
<Route path='/' component={Main}
... where to send props? />
<Route path='join' component={Join}
... props />
</Router>
问题是我需要一些 App
组件的状态变量(在 app.js
中)在 Main
和 Join
中都可用 . 如何使用路由器实现这一目标?
应用结构:
App
- Join
- Main
- ...
2 回答
这取决于你如何管理你的州 . 如果您使用Redux,您不需要在路由器中传递道具,您可以使用connect简单地访问任何组件中的redux,但是如果您不使用react,那么您可以使用Redux路由器的层次结构功能
假设你有一条这样的路线
当您访问路径时
React路由器将classHome组件作为StudentHome的子项加载,您可以简单地将props传递给classHome组件 .
你学生班的渲染方法会是这样的
关于向儿童传递道具的更多细节:How to pass props to
您可以使用标准URL参数 . 例如,要传递ID:
你需要使用browserHistory:
然后在
Join
上使用this.props.params.id
.这是一个更深入的解释https://stackoverflow.com/a/32901866/48869