【问题标题】:Using React forwardRef with Redux connect将 React forwardRef 与 Redux 连接一起使用
【发布时间】:2020-06-21 07:37:51
【问题描述】:

我有一个使用 forwardRef 的 React 功能组件,如下所示:

const wrapper = React.forwardRef((props, ref) => (
  <MyComponent {...props} innerRef={ref} />
));

export default wrapper;

现在我想使用 mapStateToProps 和 Redux 的 connect 函数向这个组件传递一些状态,如下所示:

export default connect(mapStateToProps, null)(MyComponent);

我尝试通过以下方式组合它们,但没有成功:

const wrapper = React.forwardRef((props, ref) => (
  <MyComponent {...props} innerRef={ref} />
));

export default connect(mapStateToProps, null)(wrapper);

如何将这两者结合起来以获得所需的行为?

【问题讨论】:

    标签: reactjs redux react-hooks


    【解决方案1】:

    您可以在连接函数中使用options

    connect(mapStateToProps, null, null, { forwardRef: true })(wrapper)
    

    【讨论】:

    • 我试过export default connect(mapStateToProps, null, null, { forwardRef: true })(MyComponent),但没用。问题是它找不到 innerRef 道具。如何使用connect 传递道具?
    • 如何在类组件中使用它?请问有sn-p吗?
    【解决方案2】:

    如果 MyComponent 是功能组件,请使用钩子

    这意味着您根本不需要编写连接包装器。如果您使用的是功能组件,则可以为 redux 使用钩子。

    const result : any = useSelector(selector : Function, equalityFn? : Function)
    

    const dispatch = useDispatch()
    

    【讨论】:

    • MyComponent 是一个基于类的组件
    【解决方案3】:

    可以在redux中查看连接方式的选项:https://react-redux.js.org/api/connect
    所以选项允许使用 forwardRef
    我的代码:connect(null,null,null,{forwardRef: true,})(LearnView)
    它对我有用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-05
      • 2017-12-09
      • 2018-12-05
      • 2018-06-10
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      相关资源
      最近更新 更多