我有加载多个数据集的情况;用户可以选择加载多少。所有数据集都呈现在同一个图表上。数据集单独和异步加载。
代码类似于
export const DatasetGraph = ({userSelections}) => {
const [datasets, setDatasets] = useState({});
// when a selection changes, update the data
useEffect(() => {
// while loading a dataset, it is visible but has no data
setDatasets(userSelections.map(selec => ({ dsname: [] })));
// trigger asynchronous loads for each new dataset
userSelections.forEach((dsname) => fetchDataset(dsname));
}, [userSelections]);
const fetchDataset = async (dsname) => {
response = await fetch(url + dsname);
// QUESTION: after the await, will this call the most recent version of
// the callback? Will it use the most recent datasets object or an old
// one saved in the useCallback closure?
updateDataset(dsname, response);
};
// when a fetch returns, update the empty placeholder with the real data
const updateDataset = useCallback(
// For this toy example, we could use a setState function to always
// retrieve the latest `datasets`. However, this callback may use other
// state which is really what this question is about.
(dsname, response) => setDatasets({ ...datasets, dsname: response }),
[datasets]
);
return <Graph data={datasets}></Graph>;
};
我还没有尝试让每个数据集都是一个不向 DOM 呈现任何内容的 React 组件,然后它可以管理自己的加载状态。这实际上可能更容易。