亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在導入函數中使用更高級別的 useState

如何在導入函數中使用更高級別的 useState

阿波羅的戰車 2023-03-10 15:49:00
以下代碼(為簡潔起見刪除了其中的某些部分)正在運行:function AddressInputList({  isOpen,  inputValue,  highlightedIndex,  getItemProps,  getMenuProps}: AutocompleteInputListProps) {  const [items, setItems] = useState<MarkerPoint[]>([])  const api = 'XXXX'  const fetchURL = `https://api.opencagedata.com/geocode/v1/json?key=${api}&q=${inputValue}&limit=5&pretty=1`  useEffect(() => {    async function fetchData() {      if (inputValue !== null && inputValue.length > 1) {        try {          const request = await axios.get(fetchURL)          const items = request.data.results.map((res: any) => {            return {              lat: res.geometry.lat,              lng: res.geometry.lng,              address: res.formatted            }          })          setItems(items)        } catch (error) {          console.error(error)        }      }    }    fetchData()  }, [inputValue])  return (/*Code cut out*/)}我現在想做的是重構代碼,讓它更精簡。因此,我將創建一個utility.ts-file,其中包含 -function fetchData,隨后我想將fetchData-function 導入初始AddressInputList-function:實用程序.ts:export async function fetchData(inputValue: string, fetchURL: string) {  if (inputValue !== null && inputValue.length > 1) {    try {      const request = await axios.get(fetchURL)      const items = request.data.results.map((res: any) => {        return {          lat: res.geometry.lat,          lng: res.geometry.lng,          address: res.formatted        }      })      setItems(items)    } catch (error) {      console.error(error)    }  }}現在我的問題是我不知道如何使 useState-hooksetItems在utility.ts. 我在某處讀到可以做到這一點props,但我不確定這會是什么樣子。一個簡短的例子將不勝感激!
查看完整描述

2 回答

?
MM們

TA貢獻1886條經驗 獲得超2個贊

只需創建一個自定義掛鉤即可為您獲取數據。我不建議把這個鉤子綁inputValue那么多。此外,.map 格式也不通用。


export function useFetchData(inputValue: string, fetchURL: string) {

  const [items,setItems] = useState([]);


  useEffect(() => {

    async function fetchData() {

      if (inputValue !== null && inputValue.length > 1) {

        try {

          const request = await axios.get(fetchURL)

          const items = request.data.results.map((res: any) => {

            return {

              lat: res.geometry.lat,

              lng: res.geometry.lng,

              address: res.formatted

            }

          })

          setItems(items)

        } catch (error) {

          console.error(error)

        }

      }

    }

  }, [inputValue]);


  return items;

}

之后你可以像這樣使用這個自定義鉤子


const items = useFetchData(inputValue, "/api/<endpoint>);


查看完整回答
反對 回復 2023-03-10
?
郎朗坤

TA貢獻1921條經驗 獲得超9個贊

我想您可以將 setItems 作為回調函數作為參數傳遞給您的 fetchData 函數。

fetchData(inputValue: string, fetchURL: string, setItems) {
    ...
}


查看完整回答
反對 回復 2023-03-10
  • 2 回答
  • 0 關注
  • 111 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號