Using React forwardRef with Redux connect

寵の児 提交于 2020-12-08 08:08:09

问题


I have a React functional component that is using forwardRef like this:

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

export default wrapper;

Now I want to pass some state to this component using mapStateToProps with Redux's connect function like this:

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

I tried to combine them in the following way but it didn't work:

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

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

How do I combine these two to get the desired behaviour?


回答1:


You can use options in connect function.

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



回答2:


If MyComponent is a functional component use hooks

This means that you don't need to write the connect wrapper at all. You can use hooks for redux is you're using a functional component.

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

and

const dispatch = useDispatch()


来源:https://stackoverflow.com/questions/60600130/using-react-forwardref-with-redux-connect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!