【问题标题】:React Hooks How to get to componentWillUnmountReact Hooks 如何到达 componentWillUnmount
【发布时间】:2020-06-25 23:02:30
【问题描述】:

您好,我正在尝试将以下代码传递给 reacthooks:

import { disableBodyScroll, enableBodyScroll, clearAllBodyScrollLocks } from 'body-scroll-lock';

class SomeComponent extends React.Component {
  // 2. Initialise your ref and targetElement here
  targetRef = React.createRef();
  targetElement = null;

  componentDidMount() {
    // 3. Get a target element that you want to persist scrolling for (such as a modal/lightbox/flyout/nav). 
    // Specifically, the target element is the one we would like to allow scroll on (NOT a parent of that element).
    // This is also the element to apply the CSS '-webkit-overflow-scrolling: touch;' if desired.
    this.targetElement = this.targetRef.current; 
  }

  showTargetElement = () => {
    // ... some logic to show target element

    // 4. Disable body scroll
    disableBodyScroll(this.targetElement);
  };

  hideTargetElement = () => {
    // ... some logic to hide target element

    // 5. Re-enable body scroll
    enableBodyScroll(this.targetElement);
  }

  componentWillUnmount() {
    // 5. Useful if we have called disableBodyScroll for multiple target elements,
    // and we just want a kill-switch to undo all that.
    // OR useful for if the `hideTargetElement()` function got circumvented eg. visitor 
    // clicks a link which takes him/her to a different page within the app.
    clearAllBodyScrollLocks();
  }

  render() {   
    return (
      // 6. Pass your ref with the reference to the targetElement to SomeOtherComponent
      <SomeOtherComponent ref={this.targetRef}>
        some JSX to go here
      </SomeOtherComponent> 
    );
  }
}

然后我用钩子做了以下事情:

  const [modalIsOpen, setIsOpen] = useState(false);
  const openModal = () => {
    setIsOpen(true);
  };
  const closeModal = () => {
    setIsOpen(false);
  };

  const targetRef = useRef();

  const showTargetElement = () => {
    disableBodyScroll(targetRef);
  };

  const hideTargetElement = () => {
    enableBodyScroll(targetRef);
  };

  useEffect(() => {
    if (modalIsOpen === true) {
      showTargetElement();
    } else {
      hideTargetElement();
    }
  }, [modalIsOpen]);

我不知道我是否正确地使用了 useRef 和 useEffect,但它确实有效,但我无法想象我将如何访问我的 componentWillUnmount 来调用我的:

clearAllBodyScrollLocks();

【问题讨论】:

标签: reactjs react-hooks


【解决方案1】:

componentDidMountcomponentWillUnmount 在 React Hooks 中的基本等价物是:

//componentDidMount
useEffect(() => {
    doSomethingOnMount();
}, [])

//componentWillUnmount
useEffect(() => {
   return () => {
       doSomethingOnUnmount();
   }
}, [])

这些也可以合并为一个useEffect

useEffect(() => {
    doSomethingOnMount();
    return () => {
        doSomethingOnUnmount();
    }
}, [])

这个过程称为效果清理,您可以从documentation阅读更多内容。

【讨论】:

猜你喜欢
  • 2019-09-11
  • 1970-01-01
  • 2023-03-08
  • 2019-06-14
  • 2023-04-04
  • 2020-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多