将类组件转换为函数组件时出错

如何解决将类组件转换为函数组件时出错

我正在尝试将类组件转换为功能组件。

类组件:classBasedComponent.js [此文件中包含的原始代码]

我取得的进步:

函数组件:functionComponent.js [我的进度]

这里是 GitHub 链接供参考:https://github.com/codebushi/gatsby-starter-dimension

这是我的错误:

  • 12:19 警告 'setArticle' 被分配了一个值但从未使用过 没有未使用的变量
  • 27:11 错误 'timeoutId' 未定义无未定义
  • 33:6 警告 React Hook useEffect 缺少依赖项: 'handleClickOutside'。包括它或删除依赖项 数组 react-hooks/exhaustive-deps
  • 45:30 错误 'setWrapperRef' 未定义为 no-undef
  • 58:37 警告预期为 '===',而是看到了 '==' eqeqeq
  • 66:23 错误意外使用“位置”无限制全局变量
  • 80:28 错误 'setWrapperRef' 未定义为 no-undef

我仍然遇到错误。我可以在哪里即兴发挥?

解决方法

让我们专注于错误。

27:11 错误 'timeoutId' 未定义 no-undef

您将此变量声明为 timeoutId,但在引用它时在 timeoutIdtimeOutId 之间切换。在您当前的沙箱中,它是 timeoutId,因此所有 timeOutId 用法都标记为未声明。选择其中之一并保持一致。

45:30 错误 'setWrapperRef' is not defined no-undef

80:28 错误 'setWrapperRef' is not defined no-undef

这看起来是一个由 Main 调用的函数,用于将 ref 传回 something,然后在 handleClickOutside 中引用。使用 react ref 来存储值。

const wrapperRef = React.useRef(null); // create ref to store value

...

const setWrapperRef = node => wrapperRef.current = node; // set current ref value

...

const handleClickOutside = (event) => {
  if (!wrapperRef.current.contains(event.target)) { // access current ref value
    if (isArticleVisible) {
      handleCloseArticle();
    }
  }
}

...

<Main
  isArticleVisible={isArticleVisible}
  timeout={timeout}
  articleTimeout={articleTimeout}
  article={article}
  onCloseArticle={handleCloseArticle}
  setWrapperRef={setWrapperRef} // attach ref value updater
/>

66:23 错误意外使用“位置”无限制全局变量

location 之前是通过 props 收到的,现在很可能仍然是通过 props 收到的。

<Layout location={props.location}>

或者因为我在您的功能组件中没有看到其他对 props 的引用,只需在组件签名中对其进行解构即可。如果您需要访问更多 prop 值,您也可以在此处简单地对其进行解构。

function IndexPage({ location }) { ...

现在是警告

12:19 警告 'setArticle' 被赋值但从未使用过 no-unused-vars

这只是意味着它被定义并且从未使用过,但是在检查基于类的组件时,更新 articlehandleOpenArticle 中的 handleCloseArticle 值。所以让我们在您的功能组件中做同样的事情。

这里的问题是您向 setIsArticleVisible 更新程序传递了被忽略的额外参数。 useState 更新程序不会浅合并更新,并且您的更新程序被声明为仅包含一个值。我建议还使用功能状态更新来切换布尔状态值。

handleOpenArticle(article) {
  this.setState({
    isArticleVisible: !this.state.isArticleVisible,article
  });

  setTimeout(() => {
    this.setState({
      timeout: !this.state.timeout
    });
  },325);

  setTimeout(() => {
    this.setState({
      articleTimeout: !this.state.articleTimeout
    });
  },350);
}

handleCloseArticle() {
  this.setState({
    articleTimeout: !this.state.articleTimeout
  });

  setTimeout(() => {
    this.setState({
      timeout: !this.state.timeout
    });
  },325);

  setTimeout(() => {
    this.setState({
      isArticleVisible: !this.state.isArticleVisible,article: ""
    });
  },350);
}

变成

const handleOpenArticle = (article) => {
  setIsArticleVisible(isArticleVisible => !isArticleVisible);
  setArticle(article);
  setTimeout(() => setTimeout(timeout => !timeout),325);
  setTimeout(() => setArticleTimeout(articleTimeout => !articleTimeout),350);
};

const handleCloseArticle = (article) => {
  setArticleTimeout(articleTimeout => !articleTimeout);
  setTimeout(() => setTimeout(timeout => !timeout),325);
  setTimeout(() => {
    setIsArticleVisible(isArticleVisible => !isArticleVisible);
    setArticle("");
  },350);
};

33:6 警告 React Hook useEffect 缺少依赖项: 'handleClickOutside'。包括它或删除依赖项数组 反应钩子/详尽的deps

通常您希望包含效果的所有依赖项,以便所有值都是正确的,但这里很明显意图是在组件安装时添加侦听器,并在卸载时删除它们。您可以为该行添加 eslint-disable 注释。我建议还将 timeoutId/timeOutId 声明移到效果内部,因为它不在效果外部使用。将 undefined 传递给 clearTimeout 也是安全的,它可以处理它,因此删除条件检查。

useEffect(() => {
  const timeoutId = setTimeout(() => {
    setLoading("");
  },100);

  document.addEventListener("mousedown",handleClickOutside);

  return () => {
    clearTimeout(timeoutId);
    document.removeEventListener("mousedown",handleClickOutside);
  };
  // Effect triggered on component mount only
  // eslint-disable-next-line react-hooks/exhaustive-deps
},[]);

58:37 警告预期为 '===',而是看到了 '==' eqeqeq

不确定此逻辑的来源,但已替换为上面的 wrapperRef 错误修复。

注意:

以上所有建议均完全基于您自我描述/报告的问题以及我在您的沙箱中看到的标记。解决这些问题后可能会出现其他潜在问题(可能是因为它们被它们掩盖了。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res