将数组传递给组件
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,如下所示。