本文介绍了使用 react-redux (v. 6.0.1) 在功能组件中转发 ref的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的功能组件中使用 forwardRef,该组件也使用 react-redux.我的组件如下所示:

I'm trying to use forwardRef in my functional component that is also using react-redux. My component looks like this:

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);

但是,当我尝试使用带有 ref 属性的组件时出现此错误:

However I'm getting this error when trying to use my component with a ref prop:

警告:不能为函数组件提供引用.尝试访问此引用将失败.你的意思是使用 React.forwardRef() 吗?

我做错了什么?

推荐答案

InfiniteTable 签名不正确,是 legacy context 作为功能组件中的第二个参数接收,而不是 ref.为了接收 ref 对象以与 useImperativeHandle 一起使用它,组件应该用 React.forwardRef 包装.

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.

正如参考所述,

useImperativeHandle 自定义使用 ref 时暴露给父组件的实例值.与往常一样,在大多数情况下应该避免使用 refs 的命令式代码.useImperativeHandle 应该与 forwardRef 一起使用

应该是:

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

export default connect(
  mapStateToProps,
  { fetchData },
  null,
  { forwardRef: true }
)(InfiniteTable);

这篇关于使用 react-redux (v. 6.0.1) 在功能组件中转发 ref的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 15:56