P粉3524080382023-08-16 00:58:35
The first thing that needs to be done is to change the implementation of Usage to something similar to react custom hooks
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;
Then make the following changes inside the StatsGroup component to render this data.
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;
So, to establish a link between a custom hook and the StatGroup component, first call the custom hook and then after getting the result pass the data to the StatGroup component's prop as shown below.
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;