我使用react-query来获取一些数据,在fetchlangs函数完成后,我需要调用useQuery中的fetchPagesContent函数,因为我需要动态语言的ID才能在fetchPagesContent函数中使用它,我如何使用react-query来实现
import React, { createContext,useState,useEffect } from 'react'
import { useQuery } from 'react-query'
const fetchPagesContent = async () => {
const resp = await fetch('http://127.0.0.1:8000/api/content-pages/lang_id=1');
return resp.json();
}
const fetchlangs = async () => {
const resp = await fetch('http://127.0.0.1:8000/api/languages');
return resp.json();
}
export const AppContext = createContext();
export default function AppContextProvider({children}) {
const resp = useQuery('langs',fetchlangs );
const resp = useQuery('page',fetchPagesContent);
return (
<AppContext.Provider value={resp}>
{children}
</AppContext.Provider>
)
}发布于 2021-05-12 18:50:14
您正在寻找dependent queries,只要您没有第一个查询的数据,就可以通过enabled选项禁用第二个查询:
const langs = useQuery('langs',fetchlangs );
const resp = useQuery('page',fetchPagesContent, { enabled: Boolean(langs.data) });发布于 2021-05-13 18:56:49
作为一种替代解决方案,您可以使用第三方useAsyncEffect钩子在组件中使用可取消异步效果(Live Demo)发出请求或进行任何其他异步操作:
import React from "react";
import { useAsyncEffect } from "use-async-effect2";
import cpFetch from "cp-fetch/lib/native";
/*
Note: the related network request will also be aborted
Check out your network console
*/
function* fetchAPI(url) {
const response = yield cpFetch(url);
// you can use a native fetch directly, but cpFetch wrapper will abort
// the request automatically when the async effect canceling
return yield response.json();
}
function TestComponent(props) {
const [cancel, done, result, err] = useAsyncEffect(
function* () {
this.timeout(props.timeout);
// we use mocky-delay=2s to slowdown the response for demo purpose
const data = yield* fetchAPI(
"https://run.mocky.io/v3/39486170-1983-457b-a89f-b0736ccf7961?mocky-delay=2s"
);
return yield* fetchAPI(
`https://rickandmortyapi.com/api/character/${data.fetchId}`
);
},
{ states: true }
);
return (
<div className="component">
<div className="caption">useAsyncEffect demo:</div>
<div>
{done
? err
? err.toString()
: JSON.stringify(result, null, 2)
: "loading..."}
</div>
<button className="btn btn-warning" onClick={cancel} disabled={done}>
Cancel async effect
</button>
</div>
);
}https://stackoverflow.com/questions/67501866
复制相似问题