將數組傳遞給組件
P粉006540600
2023-08-15 17:00:37
<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>
需要做的第一件事是將Usage的實作更改為類似於react自訂hook的方式
然後在StatsGroup元件內部進行以下變更以渲染這些資料。
因此,要在自訂hook和StatGroup元件之間建立鏈接,首先呼叫自訂hook,然後在取得結果後將資料傳遞給StatGroup元件的prop,如下所示。