页面呈现比获取数据并显示它更快

Page renders faster than fetching the data and displaying it

我如何使用获取调用显示我正在抓取的数据,然后将其设置到数组中并在满足条件时显示在 Dom 中。目前我渲染页面的速度比获取数据和处理数据的速度要快。

提前致谢

function Profile() {
  let myReceipe = [];
  const [isPopUp, setPopUp] = useState(false);

  ReceipeService.getReceipes().then(data => {
    myReceipe = data;
  })

  const popUpHandler = () => {
    setPopUp(!isPopUp);
  }
  return (
    <>
      <div className='profile'>
        <ProfileHeader/>
        <div className='createdposts'>
        {myReceipe.length !== 0 ? 
          <Post popUpHandler={popUpHandler} myReceipe={myReceipe}/>
          :
          null
        }
        </div> 
      </div>
      {isPopUp === true ? 
      <Magnify popUpHandler={popUpHandler}/>
      : 
      null
      }
  </>
  )
}

您的代码中有几个问题:

  • 您没有使用 useEffect 挂钩来发出 HTTP 请求
  • myReceipe 应该是你组件的状态

数据将始终在您的组件呈现后加载。

您获取数据的方式不正确。 React 有 useEffect 钩子,正是为此目的而构建的。 从服务器获取数据是一个 side-effect 并且所有副作用都属于 useEffect 钩子。因此,将发出 HTTP 请求的代码移到 useEffect 挂钩中。

还要确保 myReceipe 是组件的本地状态

const [myReceipe, setMyReceipe] = useState([]);

当来自服务器的数据可用时,更新状态以触发 re-render 以便您可以向用户显示数据。

useEffect(() => {
  ReceipeService.getReceipes()
    .then(data => {
       setMyReceipe(data);
    });
}, []);

当数据不可用时,向用户显示某种加载微调器以向用户表明数据正在加载。

只需使用状态变量 myReceipe,然后当设置 myReceipe 时,组件将重新渲染,然后在 useEffect 中调用 ReceipeService.getReceipes() :

  let myReceipe = [];
  const [isPopUp, setPopUp] = useState(false);
  const [myReceipe , setmyReceipe ] = useState([]);
  useEffect(
  ()=>{
     let isMounted=true;
      ReceipeService.getReceipes().then(data => {
        // isMounted && insures the component is still mounted
        // or else this might through an error if the component has unmounted but the api call responded  because you cant just update staet of un unmounted Component 
        isMounted && setmyReceipe(data);
      })
        return ()=>{isMounted  = false }
  },[])
  

  const popUpHandler = () => {
    setPopUp(!isPopUp);
  }
  return (
    <>
      <div className='profile'>
        <ProfileHeader/>
        <div className='createdposts'>
        {myReceipe.length !== 0 ? 
          <Post popUpHandler={popUpHandler} myReceipe={myReceipe}/>
          :
          null
        }
        </div> 
      </div>
      {isPopUp === true ? 
      <Magnify popUpHandler={popUpHandler}/>
      : 
      null
      }
  </>
  )
}