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

标签 reactjs react-router

我目前正在学习 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>
    );

客户端.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>
 );
}

扬声器.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 的内容。 - 应用程序的整个状态存储在对象树中,并且可以在路由组件之间轻松共享。

关于reactjs - 将状态作为属性传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36672009/

相关文章:

reactjs - 如何在模块化 CSS React 中更改 fontawesome 图标的颜色

javascript - 如何在渲染时显示不同的组件。我在同一页面中注册并登录

javascript - 拼接后的函数渲染和 setState()

javascript - 如何在 React.JS 中更改登录/注销时的 NavBar 文本?

javascript - React Router - 如何索引重定向到动态路由

javascript - 将 React 函数组件转换为类组件问题

javascript - 我在哪里以及如何在 reactjs 应用程序中指定全局变量

reactjs - 如何更新 React-Hooks Apollo 轮询中的变量?

javascript - React-Redux History.query 因间隔查询参数而被 chop

javascript - 现已弃用从 v4 onEnter 升级到 React router v5