简体   繁体   中英

React - HOC that returns a component which uses another HOC

I have a HOC "withFirebase" which basically provides my components an interface to communicate with Firebase Services.

Now, I am implementing another HOC "withNotificationsListener" which will receive a component and a path, and then return another component which uses the "withFirebase" HOC.

This is my first time creating a HOC which returns a component that also uses another HOC... My question is basically if this is possible with this code:

const withNotificationsListener = (WrappedComponent, notificationsDBPath) =>
  withFirebase((props) => {
    const listenNotifications = () => {};

    useEffect(() => {
      // TODO - Attach db listener subscription
      return () => {
        // TODO - Detach db listener subscription
      };
    }, []);

    return <WrappedComponent {...props} />;
  });

Following the HOC definition "function that receives a component and returns another component" this make sense to me, because, ultimately, withFirebase returns a component... but I am doubtful since lexically, strictly speaking, I do not return a component directly, but a function.

Would this way of creating this HOC be valid? Or some other way?

Seems almost correct since your props can't be Uppercase you would need to destructure them first. When you pass the Component via prop eg component={WrappedComponent}

Than in your WithNotificationListener component you can destructure it. eg const withNotificationsListener = ({component: WrappedComponent, notificationsDBPath}) =>...

That should work. The link attached goes a little more into depth why you need to destructure the prop. Destructure example

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