我编写了一段简单的代码,在页面加载时从本地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