问题描述
我正在制作显示各种图像的 next.js 应用程序:
用户点击左侧列表中的项目,右侧显示三个图像。图像基于 next.js Image 组件显示:
<Image
src={visualizationData[0]}
quality={50}
alt="Zdjęcie oryginalne"
width={600}
height={600}
/>
其中 visualizationData
是一个变量,使用 State Hook 并将 3 个 url 返回到用户想要显示的照片:
const [visualizationData,setVisualizationData] = useState(getVisualizationData(props.history.model.name,props.history.dataLists[0].replace('img/','')));
所以它返回如下内容:
一切正常,但速度很慢,因为后端需要将 .tif 照片转换为 .jpg,大约需要 3 秒。我想在这 3 秒内显示一个 spinner 或类似于微调器的东西,而不是让用户使用旧的可视化效果。
怎么做?我不知道如何检查照片是否已加载,因为我只是将网址传递给 Image 组件的 src
道具。
这是getVisualizationData(modelName,pathAndPhotoName)
的代码:
export function getVisualizationData(modelName,pathAndPhotoName) {
const photoName = pathAndPhotoName.split('/').slice(-1)[0];
const datasetPath = pathAndPhotoName.replace(`/${photoName}`,'');
const visualizationData = [
`${backendUrl}download/datasets/${datasetPath}/image/${photoName}`,`${backendUrl}download/datasets/${datasetPath}/mask/${photoName}`,`${backendUrl}download/models/${modelName}/Predictions/1/${photoName}`];
return visualizationData;
}
它正在转换照片的路径并将其返回到一个数组中。
解决方法
您可以创建一个 isLoading 布尔值。如果 isLoading 为 true,则显示 Spinner。如果没有,则数据已获取,您可以停止显示微调器并开始显示图片。
请注意,我没有关于 getVisualizationData 准确返回什么的足够信息。但基本上,它应该返回一个用获取的值解析的 Promise。所以看看这段代码,了解并应用它。
const [isLoading,setIsLoading] = useState(false);
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
const result = await getVisualizationData(props.history.model.name,props.history.dataLists[0].replace('img/','')); //Please check this line
setVisualizationData(result);
setIsLoading(false);
};
fetchData();
},[]);
然后在你的组件中,你可以在 isLoading 为真时渲染一个微调器。当它为假时,则渲染您想要显示的内容:
return(
{isLoading ? (
<SpinnerComponent />
) : (
<div>
//Render here your pictures
</div>
)}
)