与redux合成一起使用时,接收ref挂接转发的空值

fjnneemd  于 2023-02-23  发布在  其他
关注(0)|答案(1)|浏览(97)

我正在尝试将useRef详细信息从父组件传递到子组件。
如果child是一个基本组件,则它的工作方式如下。

const Apple = React.forwardRef(({
}, ref) => {
    console.log(`Apple ref: ${ref}`); // can print value, ref not null 
  return (
    <div ref={ref}>
      {`ref is: ${ref && ref.current}`}
    </div>
  );
});

export default Apple;

但是如果我使用redux和compose来 Package 组件,如下所示,ref最终会为null。
我该怎么补救呢?

import { compose } from 'redux';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';

const Apple = React.forwardRef(({
  p1,
  p2,
  p3,
}, ref) => {
  console.log(`Apple ref: ${ref}`); // no longer working, ref prints null.
  return (
    <div ref={ref}>
      {`ref is: ${ref && ref.current}`}
    </div>
  );
});

const mapStateToProps = someFunction({
  state: getState,
});

const mapDispatchToProps = {
  a: a1,
  b: a2,
  c: a3,
};

const chainUp = compose(
  withRouter,
  connect(mapStateToProps, mapDispatchToProps)
);

export default chainUp(Apple);
a9wyjsp7

a9wyjsp71#

一般来说,在现代React应用程序中,您可能不应该使用withRouterconnect。这些HOC对于向后兼容遗留类组件是必需的,但是在函数组件中,您可以(并且应该!)只使用useRouteruseSelectoruseDispatch

相关问题