简体   繁体   English

反应Redux HOC

[英]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. 我正在尝试创建一个简单的React HOC,以基于Redux状态下是否存在特定值来决定是否渲染组件。

My HOC looks something like this: 我的HOC如下所示:

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: 当我将其与路由等配合使用时,一切正常,但是对于React-Bootstrap Tabs之类的组件,我无法使用HOC将道具隐藏/传递给选项卡,如下所示:

<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. 我相信问题是由于Redux的connect() HOC返回了。 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. 我尝试通过扩展ComponentA并返回super.render()来在HOC中进行继承反转,以免在DOM树中引入connect() ,但是这样做必须处理Redux的store.getState() store.unsubscribe()

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? 如何创建此HOC以连接到redux状态,但仍返回传入的原始组件? Passing props as function args to my HOC doesn't look very good. 将props作为函数args传递到我的HOC看起来不太好。

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 与Routes一起使用时,您只需要将组件传递给Route,但是在render函数中,您需要像

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

and then in the component render method; 然后在组件render方法中;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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