【发布时间】:2016-09-03 13:13:14
【问题描述】:
这是我尝试过的一小段代码:
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 组件中的状态变量。这里的问题是,我无法读取 props 变量。 MessageBox1 组件的 getInitialState 和 ComponentDidMount 中未定义“this.props.data”。而在渲染函数中,我可以看到正确的值。我尝试了几个可以读取 getInitialState 中的道具数据的示例。为什么这里不发生这种情况?请帮忙。我在控制台中没有任何错误。
【问题讨论】:
标签: javascript jquery reactjs