【问题标题】:Reactjs - What is optimized way for multiple api calls?Reactjs - 多个 api 调用的优化方式是什么?
【发布时间】:2020-03-11 16:24:05
【问题描述】:

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

【问题讨论】:

标签: reactjs fetch use-effect


【解决方案1】:

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

https://stackoverflow.com/a/40981298/9811156

【讨论】:

    【解决方案2】:

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

    例如:

    
    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}
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-14
      • 2023-02-24
      • 1970-01-01
      • 1970-01-01
      • 2016-02-15
      • 2020-05-05
      • 1970-01-01
      相关资源
      最近更新 更多