將數組傳遞給組件
P粉006540600
P粉006540600 2023-08-15 17:00:37
0
1
566
<p>我是React的新手,需要在以下方面尋求幫助..</p> <p>我有一個元件,它接受數組列表來渲染元件,並需要一個單獨的元件來操作該數組</p> <p>渲染的組件:</p> <pre class="brush:php;toolbar:false;">export function DashboardContent() { return ( <Grid> <Grid.Col sm={12} md={12} lg={4}> <ProfileCard /> </Grid.Col> <Grid.Col sm={12} md={12} lg={8}> <Flex direction="column" h="100%" justify="space-between" gap="md"> <WelcomeCard /> <StatsGroup data={mockData} /> </Flex> </Grid.Col> <Grid.Col sm={12} md={12} lg={8}> <BalanceCard /> </Grid.Col> <Grid.Col sm={12} md={12} lg={4}> <OverviewCard /> </Grid.Col> </Grid> ); }</pre> <p>mockData是我需要透過API呼叫傳遞陣列的地方 目前傳遞以下模擬資料:</p> <pre class="brush:php;toolbar:false;">export const mockData = [ { title: 'ABC', value: '$7,999', diff: 50, }, { title: 'XXX', value: '$4,00', diff: -13, }, { title: 'Null', value: '$ 0.745', diff: 1, }, ];</pre> <p>需要一個新的元件js的幫助,可以獨立管理並進行API調用,並以模擬中描述的格式傳遞數組。</p> <p>一直在嘗試以下程式碼,但沒有成功,任何幫助將不勝感激</p> <pre class="brush:php;toolbar:false;">import React, { useEffect, useState } from 'react'; import axios from 'axios'; interface CustomArray { title: string; value: string; diff: number; } const token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; const axiosInstance = axios.create({ headers: { Authorization: `Bearer ${token}`, }, }); const Usage = () => { const [users, setUsers] = useState([]); const fetchUsers = async () => { const response = await axios.get( 'https://myrestservices.com/api/v2/organizations/AXZ/usage' ); const usersData = response.data; const usersArray = usersData.map(user => ({ title: user.title, value: user.value, diff: user.diff, })); setUsers(usersArray); }; useEffect(() => { fetchUsers(); }, []); return users; }; export default Usage;</pre> <p><br /></p>
P粉006540600
P粉006540600

全部回覆(1)
P粉352408038

需要做的第一件事是將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;
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板