【问题标题】:when using react useEffect my app is crashing使用 react useEffect 时,我的应用程序崩溃了
【发布时间】:2019-01-02 16:59:40
【问题描述】:

我正在将一个类组件更改为一个功能组件,并且我正在使用 hooks 和 useEffect 所以我的应用程序变得非常缓慢并且崩溃而没有任何错误

import React, { useState, useEffect } from 'react';
import Toolbar from '@material-ui/core/Toolbar';

const FancyToolBar = ({ children }) => {
  const [backGround, togglebackGround] = useState('white');
  const listenScrollEvent = () => {
    if (window.scrollY > 80) {
      togglebackGround('black');
    } else {
      togglebackGround('white');
    }
  };
  useEffect(() => {
    window.addEventListener('scroll', listenScrollEvent);
  });
  const logo = backGround === 'white'
    ? <img src="/images/1.jpg" alt="" style={{ width: '50px !important', height: '50px' }} />
    : <img src="/images/2.png" alt="" style={{ width: '50px !important', height: '50px' }} />;
  return (
    <Toolbar style={{ backgroundColor: backGround }}>
      {logo}
      {children}
    </Toolbar>
  );
};


export default FancyToolBar;

【问题讨论】:

  • 错误信息是什么
  • 什么版本的 React?您必须拥有最新的才能使用 Hooks

标签: reactjs react-hooks


【解决方案1】:

您需要解决两件事。

首先:你需要清理你的eventListener

第二个:仅在初始挂载时添加事件监听器,方法是将[]作为第二个参数添加到useEffect

useEffect(() => {
    window.addEventListener('scroll', listenScrollEvent);
    return () => {
      window.removeEventListener('scroll', listenScrollEvent);
    }
  }, []);

【讨论】:

  • 谢谢!第二个答案帮助我解决了我的无限问题:)
  • 谢谢先生!这个答案救了我的头
猜你喜欢
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 2020-02-07
  • 2016-03-07
  • 2014-03-15
  • 1970-01-01
  • 2019-08-11
  • 2023-03-31
相关资源
最近更新 更多