本文介绍了父级多次渲染时,如何确保商店创建仅发生一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We have a parent app which embed App.js and it will load it N times (in order to sync other embedded app)

代码 1,这是我的第一个实现.当 App() 被加载 N 次时,store 将被创建 N 次.我们只希望 store 创建一次,但可以加载 N 次.

Code 1, this is my 1st implementation. When App() is loaded N times, store will be created N times. We only want to the store to be created once, but can be loaded N times.

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 次?

In summary, how to I make sure store creation happened only once, but can be loaded for N times?

推荐答案

第二个例子中的注释提到了惰性初始状态,但这是 useState 的一个特性,而不是 useRef.所以代码会将 store.current 设置为一个函数,然后每次 App 渲染时你都会有 value={store.current()} 它将调用它函数并创建一个新的 redux 存储.所以无论如何你最终都会有 N 家商店.

The comments in your second example mention lazy initial state, but that's a feature of useState, not useRef. So the code will set store.current to be a function, and then every time App renders you have value={store.current()} which is going to call that function and create a new redux store. So you end up with N stores anyway.

我会执行以下操作之一.

I would do one of the following.

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

Option 1: use a memo with an empty dependency array

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

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

Option 2: use a state with a lazy initializer, and never set the state

const [store] = useState(createReduxStore);

这篇关于父级多次渲染时,如何确保商店创建仅发生一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:15