如何确保商店创建仅发生一次,而父项渲染多次?

时间:2020-10-05 00:06:21

标签: reactjs redux react-redux

我们有一个嵌入App.js的父应用,它将加载N次(以同步其他嵌入式应用)

代码1,这是我的第一个实现。将App()加载N次后,将创建N次存储。我们只希望商店创建一次,但是可以加载N次。

App.js
---

function App() {
    const store = createReduxStore();

    return (
        <>
            <StoreContext.Provider value={store}>
                <Component />
            </StoreContext.Provider>
        </>
    );
}


Code 2, store is a ref now, but correct me if wrong, <StoreContext.Provider value {store.current()}>. Store creation still happen N times?

App.js
---

function App() {
    // lazy loaded
    // https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
    const store = useRef(() => {
        return createReduxStore();
    });


    return (
        <>
            <StoreContext.Provider value={store.current()}>
                <Component />
            </StoreContext.Provider>
        </>
    );
}

总而言之,如何确保商店创建仅发生一次,但可以加载N次?

1 个答案:

答案 0 :(得分:0)

第二个示例中的注释提到了惰性初始状态,但这是useState的功能,而不是useRef。因此,代码会将store.current设置为一个函数,然后每次App渲染时,您都有value={store.current()},它将调用该函数并创建一个新的redux存储。因此,您最终还是要拥有N家商店。

我将执行以下操作之一。

选项1:使用带有空依赖性数组的备忘录

const store = useMemo(() => {
  return createReduxStore();
}, []);

选项2:使用带有惰性初始化程序的状态,而从不设置状态

const [store] = useState(createReduxStore);