dpp*_*dro 23 javascript reactjs
我是ReactJS的新手,并试图理解它.现在我有一种情况,我正在加载渲染所需的信息.但由于它是异步的,因此组件在将信息传递给它之前呈现自身.
var info;
function getInfo() {
//this will come from backend REST with Backbone which takes a bit
}
var InfoPage = React.createClass({
render: function() {
getInfo()
return (
<div>info: {info}</div>
);
}
});
Run Code Online (Sandbox Code Playgroud)
现在div不会显示信息值,因为它尚未在渲染中设置.那么如何让渲染等待信息呢?或者如何解决这个问题?
从顶层调用实际的React.renderComponent并触发所有子组件,所以我认为我不能强制新渲染(我不应该?).
Qus*_*uda 23
您需要执行以下操作:
var InfoPage = React.createClass({
getInitialState: function() {
return {info: "loading ... "};
},
componentDidMount: function() {
this.getInfo();
},
render: function() {
return (
<div>info: {this.state.info}</div>
);
},
getInfo:function(){
$.ajax({ url:"restapi/getInfo/whatever", .... }).success(function(res){
this.setState({info:res});
}.bind(this));
}
});
Run Code Online (Sandbox Code Playgroud)
cha*_*tic 20
ComponentDidMount 生命周期方法根据文档,componentDidMount是您应该用来执行ajax请求的组件钩子:
http://facebook.github.io/react/docs/component-specs.html#mounting-componentdidmount
ComponentDidMount
在渲染发生后立即调用...如果要与其他JavaScript框架集成,使用setTimeout或setInterval设置计时器,或发送AJAX请求,请在此方法中执行这些操作.
使用您的示例,代码可能如下所示:
var InfoPage = React.createClass({
getInitialState: function () {
return { info: {} };
},
componentDidMount: function () {
$.ajax({
url: '/info.json',
dataType: 'json',
success: function(data) {
this.setState({info: data});
}.bind(this)
});
},
render: function() {
return (
<div>info: {this.state.info}</div>
);
}
});
Run Code Online (Sandbox Code Playgroud)
getInitialState上面,我们使用该getInitialState方法返回一个空info对象.这允许我们的组件渲染,同时我们等待服务器返回数据.
一旦componentDidMount执行,它将this.setState用于替换空info数据和服务器数据并重新render组件.