我编写了一个函数来下载数据,但我认为它的工作非常慢。它应该下载一个人的名单,并收集每个人的收入。
数据:
people [{id, name, surname} x 400]incomes [{id,[{ value, date} x 60]]
const url = "https://example.com/";
const [loading, setLoading] = useState(true);
const [hasError, setErrors] = useState(false);
const [people, setPeople] = useState([]);
const useMountEffect = fun => useEffect(fun, []);
function sum(arr) {
let sum = arr.reduce((a, b) => a + b.value * 1, 0).toFixed(2);
return sum;
}
async function fetchData() {
let data = [];
try {
data = await (await fetch(url)).json();
await Promise.all(
data.map(async item => {
const res = await (await fetch(`${url+item.id}`)).json();
item.income = sum(res.incomes);
item.incomes = res.incomes;
return item;
})
);
data.sort((a, b) => b.income * 1 - a.income * 1);
setPeoples(data);
} catch (err) {
setErrors(err);
}
}
useMountEffect(() => {
fetchData().then(setLoading(false));
});发布于 2020-03-14 14:10:22
似乎您根本没有使用Promise.all返回给您的内容(它不会改变您提供给它的数据)。
同样的情况发生在sort函数中,它不修改您提供给它的数据,它只是返回一个新的数组:
let people = await Promise.all(/* the promises */)
people = poeple.sort((a, b) => b.income * 1 - a.income * 1);
setPeoples(people);性能成本很可能是由于您为每个人做了一个请求。虽然这将适用于一些项目,400将是太多。尝试从后端发送每个人的数据,可能在如下的路径上:
const url = "https://example.com/people";如果需要的话,可以单独访问它们(但是对于其他页面)。
const url = "https://example.com/people/:id";https://stackoverflow.com/questions/60683572
复制相似问题