1 回答
TA贡献1891条经验 获得超3个赞
有几种方法可以解决这个问题 - 这完全取决于您如何从 API 获取数据。如果你想将其注入到钩子中,你可以这样做 -
const DEFAULT_PROJECTS = [
{ project_id : 123, name: 'p1' },
{ project_id : 1234, name: 'p2' },
];
const useProjects = (dataFromApi) => {
// Assuming that dataFromApi is what you got back from your API call,
// and it's a dictionary keyed on the project_id.
return useMemo(() => {
return DEFAULT_PROJECTS.map(proj => {
const extraData = dataFromApi.get(proj.project_id) || {};
return {
...proj,
...extraData,
};
});
}, [dataFromApi]);
};
如果总是在变化,那么这里useMemo并不是很有帮助dataFromApi- 它每次都会重建返回的对象。
如果你想获取数据作为你的钩子的一部分,你可以这样做 -
import { useEffect, useMemo, useState } from 'react';
const DEFAULT_PROJECTS = [
{ project_id : 123, name: 'p1' },
{ project_id : 1234, name: 'p2' },
];
const useProjects = () => {
const [dataFromApi, setDataFromApi] = useState(null);
useEffect(() => {
if (!!dataFromApi) return;
// Simulate the data fetch
const fetchData = async () => {
return new Promise(resolve => {
setTimeout(() => {
const map = new Map();
map.set(123, {
field3: 'api data',
field4: 'other data',
});
setDataFromApi(map);
}, 2000);
});
};
fetchData();
}, [dataFromApi]);
return useMemo(() => {
let extraData = dataFromApi || new Map();
return DEFAULT_PROJECTS.map(proj => {
const extraFields = extraData.get(proj.project_id) || {};
return {
...proj,
...extraFields,
};
});
}, [dataFromApi]);
}
export default useProjects;
添加回答
举报