简体   繁体   中英

React Redux HOC

I'm trying to create a simple React HOC to make a decision whether to render a component or not based on whether a particular value exists in the Redux state or not.

My HOC looks something like this:

const HOC = (ComponentA, value, ComponentB) => {
    const wrapper = props => {
        props.componentDecision.key === value ? (
            <ComponentA {...props} />
        ) : (
            <ComponentB {...props} />
        );
    };

    return connect(({ componentDecision }) => ({ componentDecision }), null)(wrapper);
};

It all works okay when I use it with routes etc., but for components like React-Bootstrap Tabs , I'm unable to hide / pass props to a tab using my HOC, like so:

<Tabs ...>
 <Tab ..>
 {HOC(Tab, 'dynamicTab', null)} // passing null to hide it if value isn't dynamicTab
</Tabs>

I believe the problem is because of Redux's connect() HOC being returned. I tried doing inheritance inversion in my HOC by extending ComponentA and returning super.render() instead so as to not introduce a connect() in the DOM tree, but in doing so I have to handle Redux's store.getState() , store.unsubscribe() etc.

What could be a better way to do something like this? How can I create this HOC to be connected to the redux state but still return the original Components passed in? Passing props as function args to my HOC doesn't look very good.

When using with Routes you only need to pass the component on to the Route, However in the render function, you need to render it like

const DynamicTab = HOC(Tab, 'dynamicTab', null);

and then in the component render method;

<Tabs ...>
 <Tab ..>
   <DynamicTab />
</Tabs>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM