你可以使用React的生命周期方法来等待图像准备就绪后再渲染组件。具体来说,你可以使用componentDidMount方法来请求API并获取图像,然后使用setState更新组件状态。此时render方法会被调用并渲染出图像。
示例代码如下:
import React, { Component } from 'react';
import axios from 'axios';
class MyComponent extends Component {
state = {
image: null,
}
componentDidMount() {
// 请求API并获取图像
axios.get('https://my-api.com/image')
.then(response => {
this.setState({ image: response.data })
})
.catch(error => {
console.log(error);
});
}
render() {
const { image } = this.state;
if (!image) {
return Loading...;
}
return
;
}
}
export default MyComponent;
上一篇:API调用返回数据但不渲染