![](/img/trans.png)
[英]Rendering a component only after API request is finished React hooks
[英]Rendering react component after api response
我有一个反应组件,我希望使用 Dropbox api 填充图像。 api 部分工作正常,但组件在数据通过之前渲染,因此数组为空。 如何延迟组件的渲染,直到它拥有所需的数据?
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.不要在render方法中执行api调用,为此使用componentDidMount
生命周期方法。
在装入组件后立即调用componentDidMount()。 需要DOM节点的初始化应该放在这里。 如果需要从远程端点加载数据,这是实例化网络请求的好地方。 在此方法中设置状态将触发重新渲染。
2.使用初始值[]
在状态数组中定义imageSource
变量,一旦获得使用setState的响应更新,它将自动使用更新的数据重新呈现组件。
3.使用state数组在render方法中生成ui组件。
4.要保持渲染直到你没有获得数据,将条件放在render
方法中检查imageSource
数组的长度,如果length为零则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>
);
}
}
您应该使用组件的状态或道具,以便在更新数据时重新呈现。 对Dropbox的调用应该在render
方法之外完成,否则每次组件重新渲染时你都会遇到API。 这是你可以做的一个例子。
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = {
imageSource: []
}
}
componentDidMount() {
dbx.filesListFolder({ path: '' }).then(function(response) {
const fileList = response.entries;
this.setState({
imageSource: fileList.map(file => file.path_lower);
})
});
}
render() {
return (
<div className="folioWrapper">
{this.state.imageSource.map((image, i) => <img key={i} className="images" src={image} />)}
</div>
);
}
}
如果还没有图像,它只会以这种方式呈现空div
。
首先,您应该使用组件的状态而不使用全局定义的变量。
因此,为了避免显示具有空图像数组的组件,您需要在组件上应用条件“加载”类,并在数组不再为空时将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.