0

我有加载多个数据集的情况;用户可以选择加载多少。所有数据集都呈现在同一个图表上。数据集单独和异步加载。

代码类似于

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 组件,然后它可以管理自己的加载状态。这实际上可能更容易。

4

1 回答 1

1

useCallback使用dependencies数组检测变化

useCallback方法使用dependencies您传递给它的数组来记忆您的函数的值。每次都会重新创建您的函数,但不会分配给它,updateDataset除非其中一个dependencies已更改。

您应该谨慎使用useCallback,除非您的功能下方的组件重新渲染的成本很高,否则,useCallback如果有任何积极影响的话,不会对您的应用程序的性能产生太大的积极影响。

它的工作方式useMemo与确保您的数据(如果useCallback它是一个函数)仅在它所依赖的内容发生更改时才在您的变量上更新的方式相同。

于 2020-06-19T23:36:16.970 回答