Javascript 为什么要在没有依赖项数组的情况下使用useEffect?

Javascript 为什么要在没有依赖项数组的情况下使用useEffect?,javascript,reactjs,react-hooks,Javascript,Reactjs,React Hooks,我有以下代码: const App: React.FC = () => { const [isOpen, setIsOpen] = React.useState(true); const [maxHeight, setMaxHeight] = React.useState(); const wrapper = React.useRef<HTMLDivElement>(null); const content = React.useRef<HTMLDivE

我有以下代码:

const App: React.FC = () => {
  const [isOpen, setIsOpen] = React.useState(true);
  const [maxHeight, setMaxHeight] = React.useState();

  const wrapper = React.useRef<HTMLDivElement>(null);
  const content = React.useRef<HTMLDivElement>(null);

  const setElementMaxHeight = () => {
    if (content && content.current) {
      setMaxHeight(isOpen ? content.current.offsetHeight : 0);
    }
  };

  useEffect(() => {
   setElementMaxHeight();

    window.addEventListener("resize", setElementMaxHeight);

    return () => {
      window.removeEventListener("resize", setElementMaxHeight);
    };
  });

  const toggle = () => {
    setIsOpen(!isOpen);
  };

  return (
    <div>
      <button onClick={toggle}>
        <span className="nominal-result__expander fa" />
      </button>
      <div
        className="nominal-results__list-wrapper"
        ref={wrapper}
        style={!!maxHeight ? { maxHeight: `${maxHeight}px` } : undefined }
      >
        <div className="nominal-results__list" ref={content} />
      </div>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
const-App:React.FC=()=>{
常量[isOpen,setIsOpen]=React.useState(true);
const[maxHeight,setMaxHeight]=React.useState();
const wrapper=React.useRef(null);
const content=React.useRef(null);
常量setElementMaxHeight=()=>{
if(content&&content.current){
setMaxHeight(等参线?内容.current.offsetHeight:0);
}
};
useffect(()=>{
setElementMaxHeight();
window.addEventListener(“调整大小”,setElementMaxHeight);
return()=>{
removeEventListener(“调整大小”,setElementMaxHeight);
};
});
常量切换=()=>{
setIsOpen(!isOpen);
};
返回(
);
};
const rootElement=document.getElementById(“根”);
render(,rootElement);
这将在每个渲染上添加和删除事件处理程序

这一定不好吗?作为一个钩子,这真的有什么好处吗

这是在一次代码审查中出现的,我认为这是不好的,因为它在每个渲染中添加和删除事件侦听器。

对于这种情况,您是对的,因为
未定义的
作为
useffect
的依赖项传递

这意味着
useffect
在每个渲染上运行,因此事件处理程序将在每个渲染上不必要地分离和重新连接

函数侦听器(){
console.log('click');
}
函数示例(){
const[count,setCount]=window.React.useState(0);
window.React.useffect(()=>{
log(`adding listener${count}`);
window.addEventListener(“单击”,侦听器);
return()=>{
log(`removing listener${count}`);
removeEventListener(“单击”,侦听器);
};

});/“。事件处理程序将在每个渲染上不必要地分离和重新连接。”。这是否与我们编写没有任何挂钩的任何代码片段相同。例如,假设我们有赋值(const var=“something”),在每个渲染上,我们将使赋值工作,就好像我们有useffect(()=>const var=“something”)请不要考虑变量范围,为什么你不使用一个依赖数组而不使用一个有用的效果?@ DWJSONSTON,你会用它来运行每个渲染中需要运行的操作。这取决于你正在构建的应用程序。@ NEM,在这种情况下,你不能仅仅声明函数中的函数,而不使用UffEffE吗?ct?这取决于使用情况。渲染周期内的同步函数调用将在渲染中运行,并且可能会影响性能。效果总是在渲染后运行,因此至少对用户体验的危害较小,因为在效果开始运行时,屏幕已经显示出它应该显示的内容。