问题描述
我是ReactJS的新手,并试图了解它。现在我有一种情况,我正在加载渲染所需的信息。但由于它是异步的,因此组件在将信息传递给它之前呈现自身。
I am new to ReactJS and trying to understand it. Now I have a situation where I am loading information needed for rendering. But as it is asynchronous the component renders itself before the information is passed to it.
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>
);
}
});
现在div不显示信息值,因为它尚未在渲染中设置。那么如何让渲染等待信息呢?或者如何解决这个问题?
Now the div will not show the info-value as it is not yet set in the render. So how can I have get render to wait for the info? Or how should this be solved?
从顶层调用实际的React.renderComponent并触发所有子组件,所以我想我不能强制新渲染(我不应该't?)。
The actual React.renderComponent is called from top level and that triggers all the subcomponents so I think I cannot force new render (and I shouldn't?).
推荐答案
ComponentDidMount
生命周期方法
根据文档, componentDidMount
是您应该用来执行ajax请求的组件钩子:
ComponentDidMount
Lifecycle Method
According to the docs, componentDidMount
is the component hook you should be using to do your ajax request:
ComponentDidMount
在渲染发生后立即调用...如果要与其他JavaScript框架集成,使用setTimeout或setInterval设置计时器,或发送AJAX请求,请在此方法中执行这些操作。
Invoked immediately after rendering occurs... If you want to integrate with other JavaScript frameworks, set timers using setTimeout or setInterval, or send AJAX requests, perform those operations in this method.
Ex ample
使用您的示例,代码可能如下所示:
Example
Using your example, the code might look like this:
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>
);
}
});
getInitialState
上面,我们使用 getInitialState
方法返回一个空的 info
对象。这允许我们的组件渲染,同时我们等待服务器返回数据。
getInitialState
Above, we are using the getInitialState
method to return an empty info
object. This allows our component to render, while we wait for the server to return with data.
一旦 componentDidMount
执行,它将使用 this.setState
替换空的 info
和服务器数据并重新渲染
组件。
Once componentDidMount
executes, it will use this.setState
to replace the empty info
and the server data and re-render
the component.
您可以看到此方法用于在部分中。 github.io/react/docs/tutorial.html\">参考教程。
You can see this approach used in in the Updating state section of the React tutorial.
这篇关于ReactJS异步,等待结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!