代码之家  ›  专栏  ›  技术社区  ›  Vladislav

自定义数据上传挂钩

  •  0
  • Vladislav  · 技术社区  · 4 年前

    我编写了一段简单的代码,在页面加载时从本地json服务器请求数据。我在几个地方重复了这段代码,我想把它放在自定义挂钩中。

    告诉我如何正确编写和应用自定义钩子?

      const [data, setData] = useState()
    
      useEffect(() => {
        const getPosts = async () => {
          try {
            setData(await getData('http://localhost:3001/posts'))
          } catch (error) {
            console.log('ERROR >>', error.message)
          }
        }
        getPosts()
      }, [])
    

    我试着这样写,但没用:

    import { useEffect, useState } from "react"
    import { getData } from './../helpers'
    
    const useData = url => {
    
      const [currentData, setCurrentData] = useState()
    
      useEffect(() => {
        const getCurrentData = async () => {
          try {
            setCurrentData(await getData(url))
          } catch (error) {
            console.log('ERROR >>', error.message)
          }
        }
        getCurrentData()
      }, [url])
      
      return currentData
    }
    
    export default useData
    
    0 回复  |  直到 4 年前
        1
  •  1
  •   AMunim    4 年前

    请检查此沙盒,这似乎是每个页面加载一次数据。我只是不在里面传递URL useEffect 因为我只想在页面加载时调用它一次。

    https://codesandbox.io/s/dank-sky-6fs4rq?file=/src/useData.jsx