加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 09:35:14 所属栏目:百科 来源:网络整理
导读:我目前正在学习React路由器v1.0,我对将状态传递给子组件作为属性感到困惑. App.js getInitialState: function(){ return { status: 'disconnected',title: '' },...,render: function(){ return ( div Header title={this.state.title} status={this.state.s
我目前正在学习React路由器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,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的东西 – 应用程序的整个状态存储在对象树中,并且可以在路径组件中轻松共享.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读