将状态作为属性传递给子组件

Passing state to child components as properties

我目前正在学习 React router v1.0,我对将状态作为属性传递给子组件感到困惑。

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; 基本上我想将整个状态传递给我的路由组件而不是单独定义它们。

如有任何帮助,我们将不胜感激!

好吧,简单的答案就是不。


正如您在 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 的方法 - 您应用的整个状态都存储在一个对象树中,并且可以轻松地在您的应用程序中共享路由组件。