正文

react-redux的connect与React.forwardRef结合ref失效的解决(react泡棉回弹率)全程干货

文章摘要

文章主要讨论了在React Redux中使用`React.forwardRef`和`Connect`时遇到的问题,即在包裹组件后会导致`ref`引用失效。作者通过两种方法解决了这一问题:第一种方法是直接调用`forwardRef`返回值的`render`方法;第二种方法是在`Connect`的第四个参数中设置`forwardRef: true`,从而实现透传效果。此外,文章还提到了使用`umi-plugin-keep-alive`插件时导致的子组件`useEffect`失效问题,并通过父组件的`ref`方法和Dva框架的结合解决了这个问题。文章提供了实际应用中的解决方案,帮助开发者避免类似问题的发生。


目录react-redux的connect与React.forwardRef结合ref失效原因解决办法dva/redux的connect 和useRef/forwardRef混用的问题解决方法总结

开发中遇到connect包裹forwardRef组件后,ref引用失效,返回undefined的问题。

const CompA=React.forwardRef<OutputInterface, IProps>((props, ref)=> { ? // … }) export default connect(mapStateToProps, mapDispatchToProps)(CompA);

源码:React.forwardRef

从下面截取的源码中,可以看到forwardRef返回的是一个元素对象,包含了元素的类型REACT_FORWARD_REF_TYPE,以及渲染组件函数render方法,而connect需要的是组件,故透传出现问题。

import {REACT_FORWARD_REF_TYPE, REACT_MEMO_TYPE} from ‘shared/ReactSymbols’; export function forwardRef<Props, ElementType: React$ElementType>( ? render: (props: Props, ref: React$Ref<ElementType>)=> React$Node, ) { ? // 省略边界条件判断 ? const elementType={ ? ? $$typeof: REACT_FORWARD_REF_TYPE, ? ? render, ? }; ? if (__DEV__) { ? ? let ownName; ? ? Object.defineProperty(elementType, ‘displayName’, { ? ? ? enumerable: false, ? ? ? configurable: true, ? ? ? get: function() { ? ? ? ? return ownName; ? ? ? }, ? ? ? set: function(name) { ? ? ? ? ownName=name; ? ? ? ? if (!render.name && !render.displayName) { ? ? ? ? ? render.displayName=name; ? ? ? ? } ? ? ? }, ? ? }); ? } ? return elementType; }

方法一:调用forwardRef返回值中的render方法 

const CompA=React.forwardRef<OutputInterface, IProps>((props, ref)=> { ? // … }) // 直接通过render获取渲染组件 export default connect(mapStateToProps, mapDispatchToProps)(CompA.render);

方法二:connect第4个参数可以设置{forwardRef: true}实现透传 

const CompA=React.forwardRef<OutputInterface, IProps>((props, ref)=> { ? // … }) // 直接通过render获取渲染组件 export default connect(mapStateToProps, mapDispatchToProps, null, { ? forwardRef: true })(CompA);

因为要做table 滚动条高度缓存,所以用了umi-plugin-keep-alive插件,导致被包裹的子组件useffect失效。

故用父组件使用ref 调用子组件的getList方法实现页面更新。 但是项目用的Dva,和useRef 一起用ref会失效。

在connect 方法的第四个参数加 forwardRef: true,即可实现透传效果,其余部分不变。

其余部分用法不变。

父组件:

子组件:

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:react-redux的connect用法详解react-redux的connect示例详解react-redux中connect()方法详细解析