最近正在学习 React 钩子,现在正在做一个搜索应用程序,它必须调用 API,然后返回与我在搜索框中键入的内容相对应的列表电影。我的代码在这里:使用Fetch.jsimport { useState, useEffect } from 'react'export const useFetch = (url, initialState) => { const [data, setData] = useState(initialState) const [loading, setLoading] = useState(true) useEffect(() => { async function fetchMovies() { const response = await fetch(url) const data = await response.json() setData(data.Search) setLoading(false) } fetchMovies() }, [url]) return { data, loading }}应用程序.jsimport React, { useState } from 'react'import Search from './components/Search'import Result from './components/Result'import Loading from './components/Loading'import { useFetch } from './utils/useFetch'export default function App() { const [key, setKey] = useState('Iron man') const onSearch = (key) => { setKey(key) } const {data, loading} = useFetch(`https://www.omdbapi.com/?s=${key}&apikey=${API_KEY}`) return ( <> <Search handleSearch={onSearch}/> <Loading isLoading={loading} /> <Result movies={data}/> </> )}据我了解,单击按钮搜索函数调用 API 将被触发并按预期返回结果。我放不下const {data, loading} = useFetch(`https://www.omdbapi.com/?s=${key}&apikey=${API_KEY}`)在onSearch 函数中。遵循代码 函数调用 API 会在应用程序启动时自动调用并返回 undefined 作为结果。任何人都可以帮助我并解释原因吗?
2 回答
![?](http://img1.sycdn.imooc.com/545862770001a22702200220-100-100.jpg)
叮当猫咪
TA贡献1776条经验 获得超12个赞
也许你可以setUrl
通过以下方式暴露:
return { data, loading, onSearch: (key) => setUrl(generateUrl(key)) }
添加回答
举报
0/150
提交
取消