gpt4 book ai didi

reactjs - 正确使用 UseCallBack

转载 作者:行者123 更新时间:2023-12-04 14:15:17 25 4
gpt4 key购买 nike

目前,每次更新查询参数时,我的代码都会重新呈现。一旦我删除了查询参数;但是,我收到一条警告,指出“React Hook useCallback 缺少依赖项:'query'。要么包含它,要么删除依赖项数组 react-hooks/exhaustive-deps”。我曾尝试在 useEffect 中定义我的 getData 函数,但我将 getData 用作 useEffect 之外的 onclick 函数。我想要完成的是最初获取关于 react 钩子(Hook)的文章,然后只在提交时获取新数据,而不是在查询更新时获取新数据,并且没有任何关于查询丢失依赖项的警告。任何建议都会有很大帮助。代码如下:

import React, { useState, useEffect, useCallback } from "react"
import axios from "axios"

const Home = () => {
const [data, setData] = useState(null)
const [query, setQuery] = useState("react hooks")

const getData = useCallback(async () => {
const response = await axios.get(
`http://hn.algolia.com/api/v1/search?query=${query}`
)
setData(response.data)
}, [query])

useEffect(() => {
getData()
}, [getData])

const handleChange = event => {
event.preventDefault()
setQuery(event.target.value)
}

return (
<div>
<input type='text' onChange={handleChange} value={query} />
<button type='button' onClick={getData}>
Submit
</button>
{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

最佳答案

添加 submitting state 作为触发 axios 请求的条件

  const [submitting, setSubmitting] = useState(true)
const [data, setData] = useState(null)
const [query, setQuery] = useState("react hooks")

useEffect(() => {
const getData = async () => {
const response = await axios.get(
`http://hn.algolia.com/api/v1/search?query=${query}`
)
setData(response.data)
setSubmitting(false) // call is finished, set to false
}

// query can change, but don't actually trigger
// request unless submitting is true

if (submitting) { // is true initially, and again when button is clicked
getData()
}
}, [submitting, query])

const handleChange = event => {
event.preventDefault()
setQuery(event.target.value)
}

const getData = () => setSubmitting(true)

如果您想 useCallback ,它可以重构为:
  const [submitting, setSubmitting] = useState(true)
const [data, setData] = useState(null)
const [query, setQuery] = useState("react hooks")

const getData = useCallback(async () => {
const response = await axios.get(
`http://hn.algolia.com/api/v1/search?query=${query}`
)
setData(response.data)
}, [query])

useEffect(() => {
if (submitting) { // is true initially, and again when button is clicked
getData().then(() => setSubmitting(false))
}
}, [submitting, getData])

const handleChange = event => {
event.preventDefault()
setQuery(event.target.value)
}

并在渲染中
<button type='button' onClick={() => setSubmitting(true)}>

关于reactjs - 正确使用 UseCallBack,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60835660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com