简体   繁体   English

在 React 中包装一个沉重的非 React 组件

[英]Wrap a heavy non-React component in React

I have a large, heavy non-React component HeavyThing .我有一个又大又重的非 React 组件HeavyThing Now I'd like to wrap this component as a React component to use it inside a React app.现在我想将此组件包装为 React 组件,以便在 React 应用程序中使用它。

Two questions regarding this:关于此的两个问题:

  1. Is it correct to store the heavyThing in a state?将 heavyThing 存储在heavyThing中是否正确? I fear that when something inside heavyThing changes, the component will get re-rendered by react all the time.我担心当heavyThing中的某些东西发生变化时,组件将一直通过反应重新渲染。

  2. Data is passed into the React component using props.data , but the HeavyThing only knows clearData and addData to set new data.使用props.data将数据传递到 React 组件,但HeavyThing只知道clearDataaddData来设置新数据。 I fear that useEffect to set new data would clear and add the data many many times even if there's no new data.我担心即使没有新数据,设置新数据的useEffect也会多次清除和添加数据。 Do I need to implement some mechanism that checks whether props.data has changed?我是否需要实施某种机制来检查props.data是否已更改? How?如何?

Maybe I'm doing it completely wrong, so I'm very open to better patterns.也许我做的完全错了,所以我对更好的模式持开放态度。

export default function HeavyComponentWrapper(props) {
    const elementRef = useRef();

    const [initialized, setInitialized] = useState(false);
    const [heavyThing, setHeavyThing] = useState({});

    useEffect(() => {
        if(!initialized){
            const h = new HeavyThing();
            await h.when();
            setHeavyThing(h); // Ok to store the reference in a state?
            setInitialized(true);
        }
        heavyThing.clearData(); // Right way to ....
        heavyThing.addData(props.data); // ... update data?
    });

    return (
        <div className="targetDiv" ref={elementRef}>
        </div>
    );
}
export default function HeavyComponentWrapper(props) {
    const heavyComponentRef = useRef(new HeavyThing());

    const [initialized, setInitialized] = useState(false);

    useEffect(() => {
        h.when().then(() => setInitialized(true));
    }, []);


    useEffect(() => {
        heavyThing.clearData();
        heavyThing.addData(props.data);
    }, [props.data]);


    return (
        <div />
    );
}

or if you need to mount it in the div或者如果你需要将它安装在 div 中

export default function HeavyComponentWrapper(props) {
    const wrapperElementRef = useRef(null);
    const heavyComponentRef = useRef();

    const [initialized, setInitialized] = useState(false);

    useEffect(() => {
        heavyComponentRef.current = new HeavyThing({container: wrapperElementRef.current})
        h.when().then(() => setInitialized(true));
    }, []);


    useEffect(() => {
        heavyThing.clearData();
        heavyThing.addData(props.data);
    }, [props.data]);


    return (
        <div ref={wrapperElementRef} />
    );
}

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

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