在具有React-Redux的功能组件中转发参考(v.6.0.1)



我正在尝试在我的功能组件中使用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);

但是,当尝试将组件与ref Prop一起使用时,我会遇到此错误:

警告:无法给出函数组件。尝试访问此裁判的尝试将失败。您的意思是使用React.forwardref()?

我在做什么错?

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

作为参考状态,

使用刺激性手机自定义使用参考时会暴露于父组件的实例值。与往常一样,在大多数情况下,应避免使用REF的代码。使用刺激性应与forwardref

一起使用

应该是:

const InfiniteTable = forwardRef((props, ref) => { ... });
export default connect(
  mapStateToProps,
  { fetchData },
  null,
  { forwardRef: true }
)(InfiniteTable);

最新更新