Reactjs 如何使用公共函数处理多个useeffect钩子调用以管理唯一状态
我有一个常用的useeffect函数来处理ajax调用,如下所示: 请忽略其他内容,只关注useEffect和useState,我希望在从同一组件调用时状态不同。请参阅以下功能:Reactjs 如何使用公共函数处理多个useeffect钩子调用以管理唯一状态,reactjs,react-native,react-hooks,Reactjs,React Native,React Hooks,我有一个常用的useeffect函数来处理ajax调用,如下所示: 请忽略其他内容,只关注useEffect和useState,我希望在从同一组件调用时状态不同。请参阅以下功能: export const useFetch = ( url: string, loaderArea: string = areas.main, requestType: HttpReqestType = HttpReqestType.GET, options?: any, depArr: React
export const useFetch = (
url: string,
loaderArea: string = areas.main,
requestType: HttpReqestType = HttpReqestType.GET,
options?: any,
depArr: React.DependencyList = []
) => {
const [response, setResponse] = React.useState<any>(null);
const [error, setError] = React.useState<any>(null);
React.useEffect(() => {
const fetchData = async () => {
try {
await trackPromise(delay(200), loaderArea);
let result = null;
if (requestType === HttpReqestType.GET) {
result = await trackPromise(
API.get(url).then(response => {
if (response.status === 200 && !!response.data) {
return response.data;
} else {
console.error(url,response)
return null;
}
}),
loaderArea
);
} else if (requestType === HttpReqestType.POST) {
result = await trackPromise(
API.post(url, options).then(response => {
return response.data;
}),
loaderArea
);
}
setResponse(result);
} catch (error) {
setError(error);
}
};
fetchData();
}, depArr);
return { response, error };
}
export const useFetch=(
url:string,
loaderArea:string=areas.main,
requestType:HttpRequestType=HttpRequestType.GET,
选项?:任何,
depArr:React.DependencyList=[]
) => {
const[response,setResponse]=React.useState(null);
const[error,setError]=React.useState(null);
React.useffect(()=>{
const fetchData=async()=>{
试一试{
等待轨道承诺(延迟(200),装货区);
设result=null;
if(requestType==HttpRequestType.GET){
结果=等待跟踪承诺(
获取(url)。然后(响应=>{
if(response.status==200&&!!response.data){
返回响应数据;
}否则{
控制台错误(url,响应)
返回null;
}
}),
装载区
);
}else if(requestType==HttpRequestType.POST){
结果=等待跟踪承诺(
post(url,选项)。然后(响应=>{
返回响应数据;
}),
装载区
);
}
setResponse(结果);
}捕获(错误){
设置错误(错误);
}
};
fetchData();
},卸船);
返回{响应,错误};
}
我多次在组件中调用此函数
const TComponent: FC = () => {
const data1 =useFetch("url").response;
const data2 =useFetch("url1").response;
return (
<>
{data1 &&
data1.length > 0 &&
data1.map(el => <TCComponent key={el.id} cInfo={el} />)}
{data2 &&
data2.length > 0 &&
data2.map(el => <TCComponent key={el.id} cInfo={el} />)}
</>);
}
const t组件:FC=()=>{
const data1=useFetch(“url”)。响应;
const data2=useFetch(“url1”)。响应;
返回(
{data1&&
data1.length>0&&
data1.map(el=>)}
{data2&&
data2.length>0&&
data2.map(el=>)}
);
}
由于state或useState(在方法响应和错误中)重复,我有多个呈现错误
如何处理这些状态,以便我可以多次无误地调用它?@Dan Abramov请帮助@丹·阿布拉莫夫,请帮帮我!