简体   繁体   English

当屏幕尺寸发生变化时触发 useEffect

[英]Trigger useEffect when screen dimension has changed

I have the following useEffect我有以下useEffect

useEffect(() => {
  Draggable.create(sliderRef.current, {
    type: "x",
    bounds: {
      minX: 0,
      maxX: -document.getElementById('slider').offsetWidth + window.innerWidth
    }
  });
}, [document.getElementById('slider')])

I want to trigger it when the screen size changes I tried to pass the parameter in the dependencies array我想在屏幕大小发生变化时触发它我试图在依赖项数组中传递参数

window.innerWidth or document.getElementById('root') window.innerWidthdocument.getElementById('root')

however, without success... I appreciate help但是,没有成功......我感谢帮助

useEffect need to have a dependency that changes if you want it to re-call your callback, so having plain document.getElementById won't do the trick.如果您希望 useEffect 重新调用您的回调,则useEffect需要具有更改的依赖项,因此使用普通document.getElementById将无法解决问题。

Personally I recommend using [ResizeObserver][1] that already optimized for these type of event,我个人建议使用已经针对这些类型的事件进行了优化的[ResizeObserver][1]


const resizeObserver = new ResizeObserver(entries => {
  for (let entry of entries) {
    // ... entry has the full info about your element dimensions
     
  }
 
});

resizeObserver.observe(document.getElementById('slider'));

In React app I would use useEffect to start and stop observing the element size在 React 应用程序中,我将使用useEffect开始和停止观察元素大小

function App(){

  useEffect(() => {

    // start listening on app start
    resizeObserver.observe(document.getElementById('slider'));

    return () => {
          // clean 
          resizeObserver.unobserve(document.getElementById('slider'));
    }
  }, []);

}

You are trying to use imperative DOM code inside the React lifecycle - you can't (at least not this way).你试图在 React 生命周期中使用命令式 DOM 代码——你不能(至少不是这样)。

useEffect dependencies can only depend on variables that React tracks: state and props. useEffect依赖项只能依赖于 React 跟踪的变量:state 和 props。 React can't know when document.getElementById('slider') changes. React 无法知道document.getElementById('slider')何时更改。 It doesn't know what that is, or how to check it.它不知道那是什么,也不知道如何检查它。 The dependency-change-checking code isn't run in a loop, constantly checking variables.依赖更改检查代码不是循环运行的,而是不断检查变量。 It only runs when this component's state or props change.它仅在此组件的stateprops更改时运行。 If they don't change, React won't check the dependencies, and won't know they have changed.如果它们没有改变,React 将不会检查依赖关系,并且不会知道它们已经改变。

You should manage any code that needs to listen to window changes needs to run the old vanilla JS way.您应该管理任何需要监听 window 更改需要运行旧的 vanilla JS 方式的代码。

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

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