反应挂钩-useEffect详尽的dep-对location.hash

如何解决反应挂钩-useEffect详尽的dep-对location.hash

我有一个useEffect,它读取location.hash并基于其他依赖关系将更改哈希。看起来像这样:

useEffect(() => {
    const hashAlreadyPresent = () => {
      const hashArr = history.location.hash.split('#');
      return hashArr.includes(hashId);
    };

    const addToHash = () => {
      return history.location.hash.concat(`#${hashId}`);
    };

    const removeFromHash = () => {
      const hashArray = history.location.hash.split('#').filter(hashStr => hashStr);
      const indexOfHashId = hashArray.indexOf(hashId);
      (indexOfHashId !== -1) && hashArray.splice(indexOfHashId,1);

      return hashArray;
    };

    // if hashId props is present then attach hash in route
    hashId && !hashAlreadyPresent() && history.push({
      hash: `${hashAlreadyPresent() ? '' : addToHash()}`,search: history.location.search,});

    return () => {
      // remove hashId only,retain any other hash if present
      const hashArray = removeFromHash();
      hashId && hashAlreadyPresent() && history.replace({
        hash: hashArray.join('#'),});
    };
  },[history,hashId,history.location.hash,history.location.search]);
    

其中history来自React Router。

逻辑是,一旦组件在屏幕上(挂载),它就会向URL添加一个哈希,一旦被卸载,它将从url中删除哈希。

当然,就useEffect而言,它转换为:如果任何依赖项发生更改,则将清除先前的效果,并将使用该效果的新实例。有效的deps规则为我提供了帮助,因为早先我没有想到以下事实:如果hashId发生更改,此挂钩应清理并重新运行。

现在,我们应该完全依赖history.location.hash,但是问题是每次我从钩子中更改hash时,钩子将再次运行(先前的实例将清理并再次更改hash),这将导致无限的更新情况。

注意:我知道可以通过关闭穷举深度规则并从依赖项中排除history.location.hash来实现,但是想找出重构/分解useEffect的任何可能性,因此无需关闭即可解决。

要注意的另一件事是,如果我将history添加为依赖项(这是必须的,因为我使用的是history中的方法),那么该规则不会要求我显式添加嵌套的依存关系(history.lcoation.searchhistory.location.hash),但是,应该添加它们,因为history对象将保持不变,但嵌套的对象将随着url的更改而改变。这与您将完整props对象指定为依赖项而不是仅将所需的特定嵌套属性指定为依赖项的用例相同。

我的useEffect内是否应根据位置的更改时间来确定条件,这可以以某种方式告诉我位置是否从挂钩内部更改了,所以什么也不做?

我是否应该以不同的方式来分解和指定依赖项,以便当location.hash从效果内部更改时,效果不会运行?

注意: 在github上对此进行了讨论。有更多的见解。 https://github.com/facebook/react/issues/19636

解决方法

指定非空的依赖关系数组时,添加到依赖关系数组的任何值都将首先运行cleanup函数(在第一个渲染上除外),然后是effect函数(在卸载期间除外)。要确定是否应将值放入依赖项数组,请尝试针对该值回答以下问题:

更新此值后,效果应再次运行,例如:

  • 达到预期的效果
  • 如果需要,可以清除以前所做的任何潜在更改
  • 没有引入由于陈旧引用导致的错误?

如果以上任何要点的答案都是肯定的,则该值会将其放入依赖项数组。

我们现在可以针对useEffect函数中使用的所有值回答上述问题:

  • hashId。这是效果的主要驱动力,每次更改此值时,URL均应反映该更改。这成为效果的真理来源。因此,这是确保观察到所需效果所必需的。另外,清理以前的hashId也是必需的,因为清理功能需要引用以前的hashId
  • history。我猜想由于这是由React Router提供的,因此在组件的整个生命周期中,引用都不应更改。从这个意义上讲,在这里添加它的唯一目的是满足皮棉规则,而没有实际影响(除了额外的参照检查)。但是,如果进行更改,则效果功能将对其具有过时的引用,这可能会导致错误。这必须要照顾。
  • history.location.search。这与主要效果无关,因为只需要hashId就可以确保观察到所需的效果。也不会存在过时引用的危险,因为始终会从history对象中读取引用。由于history对象是可变的,并且每次都用最新值更新,并且已经是依赖项数组的一部分,因此可以安全地省略history.location.search。 *
  • history.location.hash,其参数与history.location.search相同。此外,始终由hashId决定history.location.hash的内容,因此不应使用对此值的更新来重新运行效果。

最后的依赖项数组仅为[hashId,history]。 **


*注意不要从search中提取history.location并在清理函数中使用search,因为这将是过时的参考

**注意到效果中使用了routeModal,如果需要,这也必须成为依赖项数组的一部分

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

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 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 -> 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("/hires") 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<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-