[英]How to properly use the UseCallback Hook
The following code gives me a warning that下面的代码给了我一个警告
React Hook useEffect has a missing dependency: 'getData'.
React Hook useEffect 缺少依赖项:'getData'。
Either include it or remove the dependency array包括它或删除依赖项数组
I know in the new rules of react I must wrap it in a useCallBack but I am unsure how to do so.我知道在新的反应规则中我必须将它包装在 useCallBack 中,但我不确定如何这样做。 Can someone please provide me with how to use, useCallBack properly.
有人可以向我提供如何使用,正确使用CallBack。 Thank you in advance!!
先感谢您!!
import React, { useState, useEffect, useCallback } from "react"
import axios from "axios"
const Home = () => {
const [data, setData] = useState(null)
const [query, setQuery] = useState("reacthooks")
useEffect(() => {
getData()
}, [query])
const getData = async () => {
const response = await axios.get(
`http://hn.algolia.com/api/v1/search?query=${query}`
)
setData(response.data)
}
const handleChange = event => {
event.preventDefault()
setQuery(event.target.value)
}
return (
<div>
<input type='text' onChange={handleChange} />
{data &&
data.hits.map(item => (
<div key={item.objectID}>
{item.url && (
<>
<a href={item.url}>{item.title}</a>
<div>{item.author}</div>
</>
)}
</div>
))}
</div>
)
}
export default Home
I would simply add the getData
function into useEffect
hook in your case instead.在您的情况下,我只是将
getData
函数添加到useEffect
钩子中。
Try the following:请尝试以下操作:
useEffect(() => {
const getData = async () => {
const response = await axios.get(
`http://hn.algolia.com/api/v1/search?query=${query}`
)
setData(response.data)
}
getData()
}, [query])
I hope this helps!我希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.