【问题标题】:REACT - Retrieve state of the parent and pass to childREACT - 检索父母的状态并传递给孩子
【发布时间】:2017-01-17 21:33:48
【问题描述】:

我正在学习 React,并且已经到了一个有点卡住的地步。这是我添加的父组件,其属性 im 用于使用 JSON 对象填充其状态:

var App = React.createClass({
    getInitialState: function() {
        return {
            clothing:{},
            order:{}
        }   
    },
    loadClothingItems: function(){
        this.setState({clothing:clothing});
    },
});

在我的 App 渲染函数中,我正在传递 loadClothingItems 的应用程序道具,如下所示:

<OtherOptions loadClothingItems={this.loadClothingItems} />

这里是子组件(OtherOptions)。有一个 onClick 填充 App 状态的标签。然后,我需要将已添加到 App 的状态返回到 OtherOptions,以便将我的所有对象键属性生成到 ul 中的 li 项中:

var OtherOptions = React.createClass({
   render:function(){
       return (
           <div className="other-options-inner">
        <a onClick={this.props.loadClothingItems}>Load Clothing</a>
               <ul>
                   {console.log(this.props.state)}
               </ul>
               </div>
       )
   } 
});

当我最初加载应用程序时,我会得到一个“未定义”的控制台日志,因为我尚未填充应用程序组件状态,但当我单击 a-tag 时,它会给我“再次未定义”。

我期待 App 的新状态在这里被传递给 OtherOptions,这样我就可以获取状态并渲染出一些 li 项目。也许我没有以正确的方式与父母沟通,或者我完全偏离了轨道,但无论哪种方式,我都被卡住了,文档也没有帮助。

谢谢

【问题讨论】:

  • 我看到在您的OtherOptions 组件中,您正在尝试访问this.props.state。当你渲染&lt;OtherOptions /&gt; 时,你是否传递了一个名为state 的道具?
  • 不,这只是我试图掌握应用程序的状态。我又是一个初学者,所以我在这里可能会偏离轨道!

标签: javascript reactjs


【解决方案1】:

如果您需要将所有状态传递给子组件,那么您可以通过 props &lt;OtherOptions items={this.state} loadClothingItems={this.loadClothingItems} /&gt; 并通过this.props.items在子组件中访问它

另外,我不确定您要在loadClothingItems 中完成什么,但clothing 不存在任何地方,因此尝试将clothing 的状态设置为服装将是未定义的。

【讨论】:

  • 就是这样,谢谢埃里克!抱歉,服装变量在我的 JSON 文件中。如果我想将状态传递给子组件,我需要每次都这样做吗?或者这不是最佳做法?
  • 如果您的应用中有大量数据,我会考虑实施 Redux,这将有助于状态管理。如果不需要所有状态,也不需要将整个状态传递给子组件。例如,如果您只需要将衣服的状态传递给孩子,则传递clothing={this.state.clothing}
猜你喜欢
  • 2019-05-07
  • 2018-06-29
  • 1970-01-01
  • 1970-01-01
  • 2018-08-04
  • 2020-04-06
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
相关资源
最近更新 更多