React.forwardRef 和 connect 联合使用报错

Unhandled Rejection (Invariant Violation): You must pass a component to the function returned by connect. Instead received {}

原来方式:

import React, { useState, useEffect, useImperativeHandle, forwardRef } from 'react';
import { connect } from 'dva';

function Child({ dispatch, onTreeSelect, myRef }) {

    const childFun = () => {
        console.log('我是 childFun')
    };
   
    useImperativeHandle(myRef, () => {
        return {
            childFun,
        }
    });

    return <div> 我是子组件 </div>
}

export default connect(({ loading }) => ({
    loading,
}))(React.forwardRef((props, ref) => {
    return <Child {...props} myRef={ref}></Child>;
}));
复制代码

修改:调整顺序,先 connect,然后再 React.forwardRef

import React, {useImperativeHandle, forwardRef } from 'react';
import { connect } from 'dva';

function Child({ dispatch, myRef }) {

    const childFun = () => {
        console.log('我是 childFun')
    };
   
    useImperativeHandle(myRef, () => {
        return {
            childFun,
        }
    });

    return <div> 我是子组件 </div>
}

// export default connect()(React.forwardRef((props, ref) => {
//     return <Child {...props} myRef={ref}></Child>;
// }));

Child = connect()(Child);

const ChildComp = React.forwardRef((props, ref) => {
    return <Child {...props} myRef={ref}></Child>;
});

export default ChildComp;
复制代码
分类:
前端
标签: