reactjs 设置参数时,API请求在React中不工作?

fafcakar  于 2023-03-01  发布在  React
关注(0)|答案(3)|浏览(99)

我试图把一个输入值作为参数在我的请求的网址,但它不更新时,我改变它,我使用模板字符串,并把状态在{},它不显示在控制台错误。

function SerchProducts() {
const [products, setproducts] = useState()
const [input, setinput] = useState()
  
  useEffect(()=>{
  axios.get(`https://dfv-ecom.eu/api/v3.1/{input}`)
  .then(res => setproducts(res.data))
  
  },[])
  
  
  
  const handleSubmit = e =>{
  setinput(e.target.name-products.value)
  }

  const fetchcart = async () => {
    setcart(await commerce.cart.retrieve())
  }
  const handleaddtocart = async(productId,quantity) => {
  
     setcart( (await commerce.cart.add(productId,quantity)))
  }
  
  return (
  <div className="cont">
  <form onSubmit={handleSubmit}>
  <input id="name-product"> type="text"
  </input>
  <button>search</button>
  </form>
  </div>
  )
  }
hmmo2u0o

hmmo2u0o1#

"你好,坎普顿"
useEffect可以是你最好的朋友也可以是你致命的敌人,小心点。
在您的情况下,您需要使用去抖动搜索。有几种方法可以实现这一点。
这将解决你的问题,但它会带你到一个黑暗的地方与其他问题,如陈旧的关闭,取消请求等。

useEffect(() => {
    axios.get(`https://dfv-ecom.eu/api/v3.1/${input}`)
    .then(res => setproducts(res.data))  
  },[input])

我强烈建议您在深入了解useEffect之前先看一下这个简短的React Hooks explained视频,以便更好地了解钩子。
有一个很好的库react-query,它可以在处理Rest API时保存很多时间,阅读这篇文章,你会学到很多东西。

s4n0splo

s4n0splo2#

根据您提供的空依赖项数组,此效果应仅在组件的初始呈现之后执行一次:

useEffect(()=>{
  axios.get(`https://dfv-ecom.eu/api/v3.1/{input}`)
    .then(res => setproducts(res.data))
}, [])

在初始渲染中,input值为undefined

const [input, setinput] = useState()

但是当我改变它的时候它不会更新
如果效果在input更改时再次执行,请将其包含在依存关系数组中:

useEffect(()=>{
  axios.get(`https://dfv-ecom.eu/api/v3.1/{input}`)
    .then(res => setproducts(res.data))
}, [input])

**编辑:**另外,语法高亮显示会识别一个输入错误。您没有正确使用模板字符串(忘记了$):

useEffect(()=>{
  axios.get(`https://dfv-ecom.eu/api/v3.1/${input}`)
    .then(res => setproducts(res.data))
}, [input])
zaq34kh6

zaq34kh63#

我认为问题可能是你没有在useEffect钩子的依赖项数组中设置你的状态输入,这个数组作为一个"观察者"工作,所以每次你的状态值发生变化时,它都会发出一个新的请求。
就像这样:

useEffect(() => {
  axios.get(`https://dfv-ecom.eu/api/v3.1/${input}`)
    .then(res => setproducts(res.data))
}, [input])

相关问题