[英]react-router-dom and redux subapp: useNavigator causes redux reload
我正在使用 react-router-dom v6。 我精通redux
並react
,但才剛剛開始使用react-router-dom
“深入”。
我有嵌套路線。 其中一個“巢”可以訪問 redux <Provider>
上下文。
盡管在Route
的“巢”中導航並可以訪問 redux 上下文,但Router
上下文中的所有渲染組件都將被重新渲染 - 並重置 redux。
最后,這種設計有幾個原因,但其中一個原因是我可以初始化給定項目的中間件(在 url 中指定)。
const middleware = (projectId) => {
let initialized = false;
return (store) => (next) => (action) => {
if (!initialized) {
initialized = true;
next({ type: "SET_READY", projectId });
}
next(action);
};
};
這是突出顯示該問題的沙盒的鏈接。
感謝@DrewReese 讓我參與到這個問題上。
在問題的沙盒描述中,我通過記憶實例化商店的 function 來解決問題。 中間件有兩步初始化過程:(1)設置項目id(2)加載store。 第二步的 store 值取決於服務器返回的內容(即,如果 null,則使用新的 store)。
// core-app.jsx
// Three versions of the store instantiation process
// 1. resets store on every new page within the project detail view (bad)
// const storeWithProject = store(projectId);
// 2. @@INIT instantiates using initialState where projectId = null (see reducer)
// const storeWithProject = useMemo(() => store(projectId), [projectId]);
// 3. The comprehensive solution
const storeWithProject = useMemo(
() => store(projectId, seedState(projectId)),
[projectId]
);
綜上所述,在實際應用程序中,我無法在<BrowserRouter>
上下文中使用 redux <Provider>
。 我無法阻止每次路由更改時重新渲染SubApp
組件(如上所述); 我依賴useEffect
在應用程序的各個點獲取數據(例如,項目列表)超出了我目前的技能:-/(prop 和 state 在 react-router 的上下文中更改是難以管理的東西)。
我現在正在研究的解決方案是“提升” redux 提供程序,以盡量減少可能觸發重新渲染的父級數量。 一個有點令人失望的結論,因為我無法利用“自然”入口點來實例化 redux 存儲。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.