使用react-redux(v.0.1.1)在功能组件中转发ref

Ine*_*esM 2 reactjs react-redux

我正在尝试forwardRef在也在使用的功能组件中使用react-redux。我的组件看起来像这样:

const InfiniteTable = ({
  columns,
  url,
  data,
  stateKey,
  loading,
  loadMore,
  fetchData,
  customRecordParams,
  ...rest
}, ref) => {
  const [start, setStart] = useState(0);
  const tableRef = React.createRef();

  console.log(rest);

  let dataSource = data;
  if (customRecordParams) dataSource = _.map(dataSource, customRecordParams);
  if (dataSource.length > FETCH_LIMIT)
    dataSource = _.slice(dataSource, 0, start + FETCH_LIMIT);

  useEffect(() => setupScroll(setStart, tableRef), []);
  useEffect(() => {
    if (loadMore) fetchData(url, stateKey, { start });
  }, [start, loadMore]);

  useImperativeHandle(ref, () => ({
    handleSearch: term => console.log(term),
    handleReset: () => console.log("reset")
  }));

  return (
    <Table
      columns={columns}
      dataSource={dataSource}
      pagination={false}
      showHeader
      loading={loading}
    />
  );
}; 

const mapStateToProps = (state, ownProps) => ({
  data: Object.values(state[ownProps.stateKey].data),
  loading: state[ownProps.stateKey].isFetching,
  loadMore: state[ownProps.stateKey].loadMore
});

export default connect(
  mapStateToProps,
  { fetchData },
  null,
  { forwardRef: true }
)(InfiniteTable);
Run Code Online (Sandbox Code Playgroud)

但是,尝试将我的组件与ref prop一起使用时出现此错误:

警告:不能为功能组件提供参考。尝试访问此引用将失败。您是要使用React.forwardRef()吗?

我究竟做错了什么?

Est*_*ask 5

InfiniteTable signature is incorrect, it's legacy context that is received as second parameter in functional components, not ref. In order to receive ref object to use it with useImperativeHandle, a component should be wrapped with React.forwardRef.

As the reference states,

useImperativeHandle customizes the instance value that is exposed to parent components when using ref. As always, imperative code using refs should be avoided in most cases. useImperativeHandle should be used with forwardRef

It should be:

const InfiniteTable = forwardRef((props, ref) => { ... });

export default connect(
  mapStateToProps,
  { fetchData },
  null,
  { forwardRef: true }
)(InfiniteTable);
Run Code Online (Sandbox Code Playgroud)