Heim > Fragen und Antworten > Hauptteil
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;