这里的子组件是一小段代码,我已经尝试了:无法读取getInitialState和ComponentDidMount道具数据对象在reactjs
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'GET',
success: function (data) {
this.setState({data: data});
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this),
cache: false
});
},
getInitialState: function() {
return {data: []};
},
componentDidMount: function() {
this.loadCommentsFromServer();
},
render: function() {
return (
<div className="commentBox">
<MessageBox1 data={this.state.data}/>
</div>
);
}
});
var MessageBox1 = React.createClass({
getInitialState: function() {
alert('MessageBox1 getInitialState');
return {nameWithQualifier: 'Mr. ' + this.props.data.pageName};
},
componentDidMount: function() {
alert('this.props.data: ' + this.props.data);
},
render: function() {
return (<div>
<div>{this.state.nameWithQualifier}</div>
<div> {this.props.data.pageName}</div>
</div>
);
}
});
ReactDOM.render(<CommentBox url="/save/6"/>, document.getElementById('content'));
在CommentBox,我查询与对象ID 6并将其传递给MessageBox1组件。我想让这个对象成为MessageBox1组件中的一个状态变量。这里的问题是,我无法读取道具变量。 “this.props.data”在MessageBox1组件的getInitialState和ComponentDidMount中未定义。而在渲染功能中,我可以看到正确的值。我已经尝试了几个能够读取getInitialState中的道具数据的例子。为什么这不在这里发生?请帮忙。我在控制台中没有任何错误。
现在,我对混乱的反应生命周期并不是一个秘密。谢谢。 – User1230321
@ user2155657不客气。我强烈建议我将链接添加到顶部,当我看到像这样的意外行为时,对我来说它总是一个很好的参考。 – jmancherje
当然。谢谢 – User1230321