reactjs 使用useFetch的多个请求

ubof19bj  于 2022-12-03  发布在  React
关注(0)|答案(1)|浏览(134)

我使用useFetch同时发送2个请求,在Safari上,响应变得混合

const [entries,setEntries] = useState([]);
const [categories,setCategories] = useState([]);

const { get, response} = useFetch('https://api.publicapis.org');

const getData = useCallback( async()=>{
    const entriesRes = await get('/entries?category=animals&https=true')
    if(response.ok)
        setEntries(entriesRes.entries)
},[])

const getCategories = useCallback( async()=>{
    const categoriesRes = await get('/categories')
    if(response.ok)
        setCategories(categoriesRes)
},[])

useEffect(()=>{
    getData();
    getCategories();
},[])

如果getCategories首先返回,则响应转到entriesRes,而不是categoriesRes,这种情况仅在safari中发生

k97glaaz

k97glaaz1#

尝试重命名useFetch结果:

const [entries,setEntries] = useState([]);
const [categories,setCategories] = useState([]);

const categoryFetch = useFetch('https://api.publicapis.org');
const dataFetch = useFetch('https://api.publicapis.org');


const getData = useCallback( async()=>{
    const entriesRes = await dataFetch.get('/entries?category=animals&https=true')
    if(response.ok)
        setEntries(entriesRes.entries)
},[])

const getCategories = useCallback( async()=>{
    const categoriesRes = await categoryFetch.get('/categories')
    if(response.ok)
        setCategories(categoriesRes)
},[])

useEffect(()=>{
    getData();
    getCategories();
},[])

相关问题