Reactjs-什么是针对多个API调用的优化方式?

我正在使用useEffect,useState和fetch。在页面加载中,我得到了一个项目ID列表。然后我基于这些ID调用api。这样,我的应用程序就会变慢,并且它们有机会在某些时候丢失数据。我正在寻找一种优化方法来解决此问题。有什么建议吗?

zml8821929 回答:Reactjs-什么是针对多个API调用的优化方式?

只需使用promise即可链接您的api调用,而不会丢失任何数据。 或者,如果可以的话,只需一次调用即可编辑API以获取项目ID和数据。

请参见https://stackoverflow.com/a/40981298/9811156

,

如果应该在多个地方使用它们,则可以外包它们并将它们用作钩子

例如:


import { usePosts } from '../hooks'

const Comp = () => {
  //                                         according to need
  const { loading: pLoading,error: pError,posts } = usePosts({ limit: 10,offset: 0 })
  // same for others
  const { loading: cLoading,error: cError,comments } = useComments(postId)

  return (
    ...someMagicStuff
  )
}

export default Comp

hooks:

const usePosts = ({ limit,offset }) => {
  const [loading,setLoading] = useState(false)
  const [error,setError] = useState(false)
  const [posts,setPosts] = useState([])

  useEffect(() => {
    setLoading(true)
    // use limit offset variables
    fetch(url)
      .then(res => res.json())
      .then(posts => {
         setPosts(posts)
         setLoading(false)  
       })
       .catch(error => setError(true))
  })

  return {loading,error,posts}

}
本文链接:https://www.f2er.com/3095000.html

大家都在问