【发布时间】: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。当你渲染<OtherOptions />时,你是否传递了一个名为state的道具? -
不,这只是我试图掌握应用程序的状态。我又是一个初学者,所以我在这里可能会偏离轨道!
标签: javascript reactjs