【发布时间】:2015-12-23 14:57:47
【问题描述】:
我有一个名为“Component_A”的父组件和一个子组件“Component_B”。我正在尝试从父组件中的服务器获取数据并将其作为道具传递给子组件。但是在我在父“Component_A”的“componentDidMount”函数中进行ajax调用之前,我的道具将没有值。所以我正在尝试使用“getDefaultProps”在子组件“Component_B”中设置 defaultProps。但是好像不行!
var Component_A = React.createClass({
componentDidMount : function(){
//Get data from server and set it in state variable called "data"
},
render : function(){
return (
<ComponentB sampleData={this.state.data} />
)
}
})
var ComponentB = React.createClass({
getDefaultProps : function (){
return {
data : {
vehicle : {
make :{
name : "Ford"
},
model : {
name : "Focus"
}
}
}
}
},
render : function(){
return (
<div> {this.props.data.vehicle.make.name} </div>
)
}
})
当我加载页面时,我得到“Uncaught TypeError: Cannot read property 'make' of undefined”
【问题讨论】:
-
我知道您没有在这里展示它,但是您是否对组件 A 的初始状态进行了任何操作?
-
@Matt 我的“getInitialState”中只返回了一个空对象。
标签: reactjs