构建高阶组件并将其应用于redux连接

时间:2018-03-27 14:32:14

标签: javascript reactjs react-native redux

请考虑React Native代码:

MyForm.js

Class MyForm extends Component{
   render(){
      //Code Left out for simplicity
   }
} 

function mapStateToProps(){//code left out for simplicity}

MyForm.propTypes = {//code left out for simplicity};
export default(connect(mapStateToProps, Actions)(withHocComponent(MyForm)));

HoComponent.js

export default withHocComponent = WrappedComponent => class HoComponent extends Component {
    class HocComponent extends Component{
       render(){
         <View>
           <WrappedComponent/>
         </View>
       }
    }
}

function mapStateToProps(state) {
return {
  prop1: state.myReducer.someProp,
 };
}

export default connect(mapStateToProps)(withHocComponent);

但是,我收到以下错误:

  

无法将类作为函数调用。

堆栈指的是这一行:export default(connect(mapStateToProps, Actions)(withHocComponent(MyForm)));

我正在尝试在redux connect函数之外实现额外的高阶组件。

2 个答案:

答案 0 :(得分:2)

好的,所以我希望这就是你要找的东西。如果您有任何问题随时问。

<强> HOC

function withHocComponent(WrappedComponent) {
    class Wrapper extends Component {
        render() {
            // here you could pass props to your wrappedComponent
            return <WrappedComponent />;
         }

        const mapStateToProps = (state) => {
           //code left out for simplicity
        }
        //connect your HOC to the store inside the Wrapper 
        return connect(mapStateToProps, {})(Wrapper);
     }
}
export default withHocComponent;

<强> MyForm的

Class MyForm extends Component{
   render(){
      //Code Left out for simplicity
   }
} 

function mapStateToProps(){//code left out for simplicity}

MyForm.propTypes = {//code left out for simplicity};

// Here is the part where the magic happens. 
// Pass your HOC your connected component
export default withHocComponent(connect(mapStateToProps, {})(MyForm)); 

答案 1 :(得分:0)

感谢@TimH, 我通过将类mapStateToProps和mapDispatchToProps放入HOC中进行了一些更改,当它们位于HOCComponent中时,我无法使其正常工作。

const HOC = (WrappedComponent) => {

    class HOCComponent extends Component {
        constructor(props) {
            super(props);
            this.state = {
                talking: false
            };
        }
        render() {
            return (<WrappedComponent speak={this.speak} />);
        }
    }


    const mapStateToProps = state => ({
        start: state.lessonStartReducer.start,
    });


    const mapDispatchToProps = dispatch => ({
        startLesson: (payload) => {
            dispatch(startLesson(payload));
        },
    });


    return connect(
        mapStateToProps,
        mapDispatchToProps
    )(HOCComponent);
}
export default HOC;