Explorar o código

fix lazy components

Khaleel Al-Adhami hai 2 semanas
pai
achega
fcb67fb8f0

+ 12 - 1
reflex/.templates/jinja/web/utils/context.js.jinja2

@@ -1,5 +1,6 @@
-import { createContext, useContext, useMemo, useReducer, useState, createElement } from "react"
+import { createContext, useContext, useMemo, useReducer, useState, createElement, useEffect } from "react"
 import { applyDelta, Event, hydrateClientStorage, useEventLoop, refs } from "$/utils/state"
+import { jsx } from "@emotion/react";
 
 {% if initial_state %}
 export const initialState = {{ initial_state|json_dumps }}
@@ -84,6 +85,16 @@ export function UploadFilesProvider({ children }) {
   );
 }
 
+export function ClientSide(component) {
+  return ({ children, ...props }) => {
+    const [Component, setComponent] = useState(null);
+    useEffect(() => {
+      setComponent(component);
+    }, []);
+    return Component ? jsx(Component, props, children) : null;
+  };
+}
+
 export function EventLoopProvider({ children }) {
   const dispatch = useContext(DispatchContext)
   const [addEvents, connectErrors] = useEventLoop(

+ 7 - 3
reflex/components/component.py

@@ -19,6 +19,7 @@ import pydantic.v1
 from rich.markup import escape
 
 import reflex.state
+from reflex import constants
 from reflex.base import Base
 from reflex.compiler.templates import STATEFUL_COMPONENT
 from reflex.components.core.breakpoints import Breakpoints
@@ -1982,7 +1983,10 @@ class NoSSRComponent(Component):
             The imports for dynamically importing the component at module load time.
         """
         # Next.js dynamic import mechanism.
-        dynamic_import = {"react": [ImportVar(tag="lazy")]}
+        dynamic_import = {
+            "react": [ImportVar(tag="lazy")],
+            f"$/{constants.Dirs.UTILS}/context": [ImportVar(tag="ClientSide")],
+        }
 
         # The normal imports for this component.
         _imports = super()._get_imports()
@@ -2015,10 +2019,10 @@ class NoSSRComponent(Component):
             else ""
         )
         return (
-            f"const {self.alias if self.alias else self.tag} = lazy(() => "
+            f"const {self.alias if self.alias else self.tag} = ClientSide(lazy(() => "
             + library_import
             + mod_import
-            + ")"
+            + "))"
         )