如何在React组件内部使用Redux connect方法并解决调用报错问题
问题原因
报错是因为你对connect的调用逻辑理解有误:connect(mapStateToProps, mapDispatchToProps)执行后返回高阶组件函数,该函数接收原组件作为入参,执行后返回的是已完成Redux绑定的React组件,而非可以直接传参执行的渲染函数。你连续多调用了一层参数传递,因此抛出is not a function错误。
需求可实现,调整方案如下
推荐方案(性能最优)
将connect逻辑提到组件外部,只执行一次生成绑定好的Redux组件,在封装组件内直接渲染即可,修正后的代码:
// ReduxWrapper.tsx import React from 'react' import {connect} from 'react-redux' interface SomeOtherComponentProps { foo?: string, bar?: string } function SomeOtherComponent({foo, bar}: SomeOtherComponentProps) { return ( <div> This is a component with foo={foo} and bar={bar}! </div> ) } // connect逻辑移到组件外,仅执行一次 const mapStateToProps = (state: {}) => ({ // @ts-ignore foo: state.foo }); const ConnectedSomeOtherComponent = connect(mapStateToProps, {})(SomeOtherComponent) export default function ReduxWrapper( child_props: SomeOtherComponentProps ): React.ReactElement { // 直接渲染已绑定Redux的组件,透传所有props return <ConnectedSomeOtherComponent {...child_props} /> }
App.tsx代码无需调整,保持原有写法即可正常运行。
特殊场景方案(需动态生成mapState)
如果你的mapStateToProps需要依赖ReduxWrapper内部的动态参数,必须在组件渲染时生成绑定组件,可以用React.createElement调用生成的绑定组件:
export default function ReduxWrapper( child_props: SomeOtherComponentProps ): React.ReactElement { const mapStateToProps = (state: {}) => ({ // 可在这里使用ReduxWrapper内部的动态参数生成映射规则 // @ts-ignore foo: state.foo }); const ConnectedComponent = connect(mapStateToProps, {})(SomeOtherComponent) return React.createElement(ConnectedComponent, child_props) }
注:该方案每次组件渲染都会重新执行connect生成新组件,性能较差,非必要不推荐使用
内容的提问来源于stack exchange,提问作者Sasgorilla
相关产品推荐
相关产品推荐

