首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >反应功能部件卸载

反应功能部件卸载
EN

Stack Overflow用户
提问于 2022-03-28 11:45:53
回答 1查看 377关注 0票数 1

我想将这个组件demo/src/JSONEditorReact.js或React.js重写为一个功能组件。我做了这个:

代码语言:javascript
复制
const Editor = ({json, mode, onChange}) => {
  const elRef = useRef(null);

  useEffect(() => {
    const options = {
      onChangeText: onChange,
      onChangeJson: onChange,
    };

    const jsonEditor = new JSONEditor(elRef.current, options);
    if (jsonEditor) {
      if (json) {
        jsonEditor.set(json);
      }

      if (mode) {
        jsonEditor.setMode(mode);
      }
    }

    return () => {
      if (jsonEditor) {
        jsonEditor.destroy();
      }
    }
  },[json,mode]);
  
  return (
    <div
      className={styles.jsoneditor_react_container}
      ref={elRef}
    />
  )
}

export default Editor;

我的问题是:在带有json、模式依赖的useEffect中卸载组件useEffect是正确的吗?还是应该创建另一个带有空依赖数组的useEffect,以获得与类组件相同的行为?

EN

回答 1

Stack Overflow用户

发布于 2022-03-28 12:01:25

只要销毁和重建JSONEditor不需要明显的时间或引起用户明显的视觉抽搐,您所做的一切都是好的。当组件被卸载时,编辑器将被清除。

但是,由于它似乎允许您更改现有实例(基于API)上的模式和JSON,所以我认为我应该这样做,而不是在这些更改时完全销毁并重新构建它:

代码语言:javascript
复制
const Editor = ({json, mode, onChange}) => {
  const elRef = useRef(null);
  const edRef = useRef(null);

  useEffect(() => {
    // On mount
    const options = {
      onChangeText: onChange,
      onChangeJson: onChange,
    };

    const jsonEditor = edRef.current = new JSONEditor(elRef.current, options);
    if (json) {                 //
      jsonEditor.set(json);     // I don't think you actually need these here,
    }                           // I *think* `useEffect` callbacks are run in
    if (mode) {                 // order so the below will do it. But...
      jsonEditor.setMode(mode); //
    }                           //

    return () => {
      // No `if`, you *know* it exists
      jsonEditor.destroy();
      edRef.current = null;
    }
  }, []);

  useEffect(() => {
    const jsonEditor = edRef.current;
    if (!jsonEditor) { // I don't think this can happen
      return;
    }
    if (json) {
      jsonEditor.set(json);
    }
    if (mode) {
      jsonEditor.setMode(mode);
    }
  }, [json, mode]);
  
  return (
    <div
      className={styles.jsoneditor_react_container}
      ref={elRef}
    />
  );
};

export default Editor;

但这更复杂,因此,如果您正在做的工作很好,并提供您想要的用户体验,您可能想不谈它。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71646942

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档