【问题标题】:How do i change the value of a params query in an api?如何更改 api 中参数查询的值?
【发布时间】:2022-11-21 22:20:14
【问题描述】:

我对如何像 API 上的 filter 算法那样实时更改 params 的值感到困惑。每次我更改值时,请求的数据也会更改,当我将硬编码的字符串放在 params 上时,它会响应一些数组,但当我使用 useState 时,它​​不会。

import {useForm} from 'react-hook-form'
import List from './List'
import axios from 'axios'

const url = 'https://api.coingecko.com/api/v3/search'

export default function SearchField(){
  const {register ,watch, handleSubmit , formState:{error}} = useForm()
  const [query ,setQuery] =useState('bitcoin')
  
  const fetchQuery = async (e) => {
    try{
      const {data} = await axios(url,
        {params:{query: `{${query}}`}},
        {headers:{Accept: 'Application/json'}})
        console.log(data)
        console.log(query)
      }catch(error){
      console.log(error)
    }
  }

  useEffect(()=>{
    fetchQuery()
  },[])
  return(<>
   <form onSubmit={handleSubmit(data => console.log(data))}>
     <input {...register('coinSearch')}/> 
   </form>
   <List search={[]}/>
  </>)
}```


as seen in the code above `query:` has variable of query but it does not changes the value.

P.S I'm trying to use `watch()` to read realtime the `<input>` but still nothing 

【问题讨论】:

  • 你好,query什么时候变?根据您的代码,fetching 仅在首次加载时执行,而不是在更改 query 时执行。
  • 我想每次输入一个字符串时更改query的值我想让它像filter()但是在API内部并提取与我输入的字符串相同的值

标签: reactjs api filter


【解决方案1】:

删除fetchQuery并更新useEffect,如下所示,在更改query时执行fetching

useEffect(()=>{
  (async () => {
    try{
      const {data} = await axios(url,
        {params:{query: `{${query}}`}},
        {headers:{Accept: 'Application/json'}})
        console.log(data)
        console.log(query)
      }catch(error){
      console.log(error)
    }
  })()
},[query])

希望这可以解决您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 2019-05-14
    相关资源
    最近更新 更多