[英]React - HOC that returns a component which uses another HOC
我有一個 HOC“withFirebase”,它基本上為我的組件提供了一個與 Firebase 服務通信的接口。
現在,我正在實現另一個 HOC“withNotificationsListener”,它將接收一個組件和一個路徑,然后返回另一個使用“withFirebase”HOC 的組件。
這是我第一次創建一個 HOC,它返回一個也使用另一個 HOC 的組件......我的問題基本上是這個代碼是否可能:
const withNotificationsListener = (WrappedComponent, notificationsDBPath) =>
withFirebase((props) => {
const listenNotifications = () => {};
useEffect(() => {
// TODO - Attach db listener subscription
return () => {
// TODO - Detach db listener subscription
};
}, []);
return <WrappedComponent {...props} />;
});
遵循 HOC 定義“接收一個組件並返回另一個組件的函數”這對我來說是有意義的,因為最終 withFirebase 返回一個組件......但我很懷疑,因為從詞匯上嚴格來說,我不直接返回一個組件,但是一個 function。
這種創建此 HOC 的方式是否有效? 還是其他方式?
似乎幾乎是正確的,因為你的道具不能是大寫的,你需要先解構它們。 當您通過 prop 傳遞組件時,例如 component={WrappedComponent}
比在您的 WithNotificationListener 組件中,您可以解構它。 例如 const withNotificationsListener = ({component: WrappedComponent, notificationsDBPath}) =>...
那應該行得通。 附加的鏈接更深入地解釋了為什么需要解構道具。 解構示例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.