一起学习网 一起学习网


react-redux的connect与React.forwardRef结合ref失效的解决

网络编程 react-redux的connect,React.forwardRef,connect与React.forwardRef结合ref失效 06-18

react-redux的connect与React.forwardRef结合ref失效

开发中遇到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);

dva/redux的connect 和useRef/forwardRef混用的问题

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

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

解决方法

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

其余部分用法不变。

  • 父组件:

  • 子组件:

总结

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


编辑:一起学习网

标签:组件,方法,的是,包裹,源码