问题描述
我有一个反应组件,我希望使用Dropbox api填充图像。 api部分工作正常,但组件在数据通过之前呈现。所以数组是空的。如何才能延迟组件的渲染,直到它有所需的数据?
I have a react component that I wish to populate with images using the Dropbox api. The api part works fine, but the component is rendered before the data comes through & so the array is empty. How can I delay the rendering of the component until it has the data it needs?
var fileList = [];
var images = [];
var imageSource = [];
class Foo extends React.Component {
render(){
dbx.filesListFolder({path: ''})
.then(function(response) {
fileList=response.entries;
for(var i=0; i<fileList.length; i++){
imageSource.push(fileList[0].path_lower);
}
console.log(imageSource);
})
for(var a=0; a<imageSource.length; a++){
images.push(<img key={a} className='images'/>);
}
return (
<div className="folioWrapper">
{images}
</div>
);
}
}
感谢您的帮助!
推荐答案
更改:
1。不要这样做api调用内部渲染方法,使用 componentDidMount
生命周期方法。
1. Don't do the api call inside render method, use componentDidMount
lifecycle method for that.
:
componentDidMount:
2。定义 imageSource
状态数组中的变量,初始值 []
,一旦获得使用 setState ,它会自动重新渲染组件更新数据。
2. Define the imageSource
variable in state array with initial value []
, once you get the response update that using setState, it will automatically re-render the component with updated data.
3. 使用状态数组在render方法中生成ui组件。
3. Use the state array to generate the ui components in render method.
4。要保持渲染,直到你没有得到数据,把条件放在 render
方法中检查长度 imageSource
数组如果长度为零则返回null
。
4. To hold the rendering until you didn't get the data, put the condition inside render
method check the length of imageSource
array if length is zero then return null
.
这样写:
class Foo extends React.Component {
constructor(){
super();
this.state = {
imageSource: []
}
}
componentDidMount(){
dbx.filesListFolder({path: ''})
.then((response) => {
let fileList = response.entries;
this.setState({
imageSource: fileList
});
})
}
render(){
if(!this.state.imageSource.length)
return null;
let images = this.state.imageSource.map((el, i) => (
<img key={i} className='images' src={el.path_lower} />
))
return (
<div className="folioWrapper">
{images}
</div>
);
}
}
这篇关于api响应后渲染反应组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!