我目前正在学习React路由器v1.0,我对将状态传递给子组件作为属性感到困惑. App.js getInitialState: function(){ return { status: 'disconnected', title: '' }, ... , render: function(){ return ( div Header title={this.s
App.js
getInitialState: function(){ return { status: 'disconnected', title: '' }, ... , render: function(){ return ( <div> <Header title={this.state.title} status={this.state.status}/> {React.cloneElement(this.props.children,{title:this.state.title,status:this.state.status})} </div> );
Client.js
var routes = ( <Router history={hashHistory}> <Route path="/" component={App}> <IndexRoute component={Audience} /> <Route path ="speaker" component={Speaker} /> </Route> </Router> );
Audience.js
render: function(){ return( <div> <h1>Audience</h1> {this.props.title || "Welcome Audience"} </div> ); }
Speaker.js
render: function(){ return( <div> <h1>Speaker:</h1> {this.props.status || "Welcome Speaker!"} </div> ); }
而不是这样做:
{React.cloneElement(this.props.children,{title:this.state.title,status:this.state.status})}
使用https://facebook.github.io/react/docs/jsx-spread.html运算符的React.cloneElement是否有类似的东西:
<RouteHandler {...this.state}/>
TLDR;基本上我想将整个状态传递给我的Route Components而不是单独定义它们.
任何帮助将不胜感激!
嗯,简单的答案就是没有.正如你在this comment中看到的那样 – 有一些方法可以实现这种行为(你正在做的就是其中之一),也许你已经看过所有这些行为,但我不建议你使用任何一种他们,除非真的有必要.
您应该在以下主题中检查这些讨论:
https://github.com/reactjs/react-router/issues/1857
https://github.com/reactjs/react-router/issues/1531
@ryanflorence [Co-author of React-router]
You should think of your route components as entry points into the app
that don’t know or care about the parent, and the parent shouldn’t
know/care about the children.
通常,处理这些情况的最佳方法是使用类似redux的东西 – 应用程序的整个状态存储在对象树中,并且可以在路径组件中轻松共享.