P粉3524080382023-08-16 00:58:35
需要做的第一件事是將Usage的實作更改為類似於react自訂hook的方式
const useApiData = (apiUrl) => { const [data, setData] = useState([]); const fetchData = async () => { try { const response = await axios.get(apiUrl); const responseData = response.data; const dataArray = responseData.map(item => ({ title: item.title, value: item.value, diff: item.diff, })); setData(dataArray); } catch (error) { console.error('Error fetching data:', error); } }; useEffect(() => { fetchData(); }, [apiUrl]); return data; }; export default useApiData;
然後在StatsGroup元件內部進行以下變更以渲染這些資料。
const StatsGroup = ({ apiData }) => { return ( <div> {apiData.map(item => ( <div key={item.title}> <p>Title: {item.title}</p> <p>Value: {item.value}</p> <p>Diff: {item.diff}</p> </div> ))} </div> ); }; export default StatsGroup;
因此,要在自訂hook和StatGroup元件之間建立鏈接,首先呼叫自訂hook,然後在取得結果後將資料傳遞給StatGroup元件的prop,如下所示。
const DashboardContent = () => { // 使用您想要从中获取数据的任何API URL const apiUrl = 'https://myrestservices.com/api/v2/organizations/AXZ/usage'; const apiData = useApiData(apiUrl); return ( <div> <h1>Stats Group</h1> <StatsGroup apiData={apiData} /> </div> ); }; export default DashboardContent;