StructureBuilder / react-keep-alive

A component that maintains component state and avoids repeated re-rendering.
MIT License
984 stars 106 forks source link

New implementation #132

Open alessandro308 opened 2 years ago

alessandro308 commented 2 years ago

I tried it but there was several errors with the latest versions of React. At the end, I achieved basically the same result using https://github.com/httptoolkit/react-reverse-portal and building some component around it.

Basically I just created a Provider that store a list of mounted components (the core function is):

mountComponent(
        key, children,
) {
        const {components} = this.state;
        if(!components[key]){
            const node = createHtmlPortalNode();
            this.setState(({ components }) => ({
                components: {
                    ...components,
                    [key]: [node, children],
                },
            }));
            return node;
        } else {
            let node = components[key][0];
            this.setState(({ components }) => ({
                components: {
                    ...components,
                    [key]: [node, children],
                },
            }));
            return node;
        }
  }

and the render is like

<KeepALiveContext.Provider value={this.value}>
                {
                    Object.entries(components)
                    .map(([key, [node, component]]) =>
                        <InPortal node={node} key={key}>
                            {component}
                        </InPortal>
                    )
                }
                { children }
</KeepALiveContext.Provider>

and then I invoke this function in the KeepAlive component using the useEffect.

Since this implementation uses react-reverse-portal I can use the standard useEffect hooks my component and all looks like super.

What do you think to consider to rewrite react-keep-alive with this suggestion so to be more compatible with latest version of React and then remove all the event communication inside of it?

shenjunru commented 2 years ago

Give a try react-fiber-keep-alive, the react fiber based keep-alive implementation.