【发布时间】:2020-09-20 07:53:34
【问题描述】:
基本上在我的 App.js 中,我需要调用 useFetch 两次来显示两个表的微调器/数据/错误。
如何区分哪个微调器/数据/错误是针对哪个表的?因为在 useEffect 我回来了 { data, loading, error },在 App.js 中,我得到的值是这样的 const { data, loading, error } = useFetch(url_order, date)。但我想要 const { data_table1, loading_table1, error_table1 } = useFetch(url_order, date)。
这是我的 useFetch 自定义钩子
import { useState, useEffect } from "react";
export default function useFetch(url, date) {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
useEffect(() => {
const doFetch = async () => {
setLoading(true);
try {
const res = await fetch(url);
const json = await res.json;
setData(json.result.result);
} catch (error) {
setError(true);
}
setLoading(false);
};
doFetch();
}, [date]);
return { data, loading, error };
}
这是我的 App.js
import React from "react";
import useFetch from "./hooks/useFetch";
import OrderTable from "./OrderTable";
import IngredientTable from "./IngredientTable";
const App = () => {
const { data, loading, error } = useFetch(url_order, date);
const { data, loading, error } = useFetch(url_ingredient, date);
return (
<div>
{loading ? (
<BeatLoader css={override} color={"#36D7B7"} loading={loading} />
) : error ? (
<h3>Failed to fetch data for Order's table</h3>
) : (
<OrderTable data={data} />
)}
{loading ? (
<BeatLoader css={override} color={"#36D7B7"} loading={loading} />
) : error ? (
<h3>Failed to fetch data for Ingredient's table</h3>
) : (
<IngredientTable data={data} />
)}
</div>
);
};
export default App;
【问题讨论】:
标签: reactjs react-hooks