繁体   English   中英

使用 React 钩子防止 React 重新渲染 D3 图表

[英]Using React hooks to prevent React re-rendering of a D3 chart

我一直在分别使用 React 和 D3,现在有一个项目,我需要对应用程序的绘图功能进行低级别控制。 基本上,我需要能够在用户放大时从数据库中获取更高分辨率的数据,反之亦然。

我找到了几种将 D3 和 React 结合使用的方法。 我想尝试保留基于 hooks API 的所有 React 代码,因为它用于其余代码库。 我正在努力为我面临的特定情况获得等效的钩子。 React hooks 的文档很棒,但我认为我的情况更像是一个边缘案例,我没有看到任何与我所拥有的类似用例相关的讨论。

代码的逻辑相当简单:我有一个主容器,称为 App.js,它保存一些状态。 App.js 呈现一个 Wrapper 组件(这是发生挑战的地方),然后 Wrapper.js 文件简单地创建 D3 Plot。 D3 图只是带有一些缩放事件的线图的典型 D3 代码。

包装器代码:

import React, { Component } from 'react';
import Plot from './Plot'; // D3 plot

class Wrapper extends Component {

    // Sets up plot when Wrapper first added to DOM tree
    componentDidMount(){
        this.setState({
            plot: new Plot(this.refs.plot, this.props.data, this.props.updateData)
        });
    };

    // Do not allow React to re-render the Wrapper and therefore the Plot
    shouldComponentUpdate(){
        return false;
    };

    // When the data prop changes, execute the update() method in the plot file
    componentWillReceiveProps(nextProps){
        this.state.plot.update(nextProps.data) // the .update() method calls props.updateData()
    }

    render(){
        return <div ref="plot"></div>
    }
}

export default Wrapper;

我已经开始将下面的钩子版本放在一起,但我无法提出合适的方法来满足我对 shouldComponentUpdate 和 componentWillReceiveProps 块的情况所追求的特定要求。

钩子版本:

import React, { useEffect, useRef } from 'react';
import Plot from './Plot'; // D3 plot

const Wrapper = props => {

    // destruct props
    const { 
        data = props.data,
        fields = props.fields,
        click = props.click
    } = props

    // initialise empty ref
    const plotRef= useRef(null);

    // ComponentDidMount translated to hooks
    useEffect(() => {
        new Plot(plotRef, data, updateData)
    },[]) // empty array ensures the plot object is only created once on initial mounting

    // shouldComponentUpdate
    useEffect(...) // This won't work because render has already occurred before useEffect dependency array diffed?

    // ComponentWIllReceiveProps
    useEffect(() => {
        plot.update(data)
    }, [data]) // This won't work because component needs to have re-rendered

    return (
        <div ref= {plotRef}></div>
    )


};

export default Wrapper;

我想要实现的是在初始安装后阻止 D3 图表的任何渲染,但是如果父组件中的数据道具发生变化,则在 D3 类中执行一个方法,而不允许 React 重新渲染 Wrapper 组件。

这是可能的还是我最好将它作为基于类的组件?

我一直在用头撞墙试图获得逻辑但没有任何成功,因此任何输入都将不胜感激。

您可以使用合适的依赖项将返回值包装在 React useMemo 中。

https://reactjs.org/docs/hooks-reference.html#usememo

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM