ZBLOG

import React, { useEffect, useState } from 'react' import './index.less' import Contact from './contact' import { initContact } from '@/api/handlers/common.api' import { initDataOrigin } from './mock' import hua from '@hweb/hua-js' import Services...

在您的代码中,组件会在初始加载时调用 initContact 函数来获取数据。如果此请求尚未完成,initDataContent 的初始值为 undefined。根据您现有的逻辑,当 initDataContent?.hotelStatus 不是 ‘1’ 时,会渲染 <Empty /> 组件。这可能导致在数据还未加载完成之前显示空状态。

要避免这种情况,您可以添加一个加载状态,以便在等待数据时显示一个加载指示器,而不是直接渲染 <Empty />。以下是如何实现的步骤:

  1. 添加一个新的状态变量以跟踪加载状态。
  2. 在发送请求之前,将加载状态设置为 true,并在请求完成后将其设置回 false
  3. 在返回的 JSX 中根据加载状态条件渲染相应的内容。

修改后的代码如下:

  1. import React, { useEffect, useState } from 'react'
  2. import './index.less'
  3. import Contact from './contact'
  4. import { initContact } from '@/api/handlers/common.api'
  5. import { initDataOrigin } from './mock'
  6. import hua from '@hweb/hua-js'
  7. import ServicesDesc from './servicesDesc/servicesDesc'
  8. import Empty from './empty'
  9. const Home = (props) => {
  10. const [initDataContent, setInitDataContent] = useState()
  11. const [loading, setLoading] = useState(true) // 新增 loading 状态
  12. useEffect(() => {
  13. hua.setNavigationBarTitle('联系酒店')
  14. let params = {
  15. hotelId: props?.query?.hotelId,
  16. }
  17. for (const key in params) {
  18. if (Object.hasOwnProperty.call(params, key)) {
  19. !params[key] && delete params[key]
  20. }
  21. }
  22. initContact(params)
  23. .then((res) => {
  24. if (res?.businessCode === '1000') {
  25. console.log('initDataOrigin', initDataOrigin)
  26. setInitDataContent(res?.content)
  27. }
  28. })
  29. .finally(() => {
  30. setLoading(false) // 请求结束后更新 loading 状态
  31. })
  32. }, [])
  33. const renderPage = () => {
  34. if (loading) { // 当 loading 为 true 时显示加载中的内容
  35. return <div>正在加载...</div>
  36. }
  37. if (initDataContent?.hotelStatus === '1') {
  38. return (
  39. <>
  40. <div className="home-backgroundImg">
  41. <Contact content={initDataContent}></Contact>
  42. <ServicesDesc serviceIntroductionList={initDataContent?.serviceIntroductionList}></ServicesDesc>
  43. </div>
  44. <div className="footer">
  45. <div
  46. className="footer-btn"
  47. onClick={() => {
  48. const { hotelId } = props?.query
  49. console.log('hotelId ', hotelId)
  50. $tools.handleToService(hotelId)
  51. }}
  52. >
  53. 前往服务频道,使用服务
  54. </div>
  55. </div>
  56. </>
  57. )
  58. } else {
  59. return <Empty></Empty>
  60. }
  61. }
  62. return <div className="home">{renderPage()}</div>
  63. }
  64. export default Home;

这样一来,在数据还没有返回之前,会显示 “正在加载…” 而不是 <Empty />,从而提供更好的用户体验。你可以根据需要自定义这个加载提示的信息或样式。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=20857

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?