簡體   English   中英

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

[英]React - How to use higher-level useState in imported functions

下面的代碼(為了簡潔起見,它的某些部分被剪掉了)正在工作:

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 fetchData文件,其中包含fetchData函數,隨后我想將fetchData函數導入到初始AddressInputList函數中:

實用程序.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-hook setItemsutility.ts可用。 我在某處讀到這可以用props來完成,但我不確定這會是什么樣子。 一個簡短的例子將不勝感激!

只需創建一個可以為您獲取數據的自定義掛鈎。 我不建議將這個鈎子與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>);

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM