我想封裝一個 npm React 組件,并且我想使用 Redux 來管理這個 React 組件內部的狀態。
當另一個 React 專案匯入我的組件時,這個 React 專案的 redux 實體是否會與我的 React 組件沖突?
這是示例:組件將如下所示:
// File Explorer Component, will be build into a npm package
import React from "react";
import { Provider } from "react-redux";
import { store } from "./store";
function FileExplorer({source}) {
<Provider store={store}>
{/* there will be complicated business logic inside */}
</Provider>;
}
然后,我創建另一個 React 專案,并FileExplorer從 npm 匯入組件
索引.jsx
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { store } from "./store"; // this store is a different one
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<Provider store={store}>
<App />
</Provider>
</StrictMode>,
rootElement
);
應用程式.jsx
import FileExplorer from 'file-explorer';
export default function App() {
return (
<div className="App">
<FileExplorer source={'https://example.com/data/v1/files'} />
</div>
);
}
uj5u.com熱心網友回復:
這里有幾個想法。
第一個是肯定的,如果嵌套在其中的組件<FileExplorer>也需要訪問應用程式范圍的 Redux 存盤,這絕對會導致沖突,因為默認情況下,所有 Redux 連接的 React 組件都通過 React 背景關系訪問同一個存盤實體。
從技術上講,可以將備用背景關系傳遞給<Provider>并創建useSelector/useDispatch從該背景關系讀取存盤的自定義版本:
https://react-redux.js.org/using-react-redux/accessing-store#providing-custom-context
盡管看起來我們實際上并沒有記錄用于創建選擇器掛鉤 atm 的背景關系定制版本的 API。
React-Redux 應該是匯出createSelectorHook和createDispatchHooks函式,你可以在這里看到它們的使用:
https://github.com/reduxjs/react-redux/blob/v7.2.6/src/hooks/useSelector.js#L166
應該用作:
const useCustomContextSelector = createSelectorHook(MyCustomContext);
說了這么多:我仍然傾向于在useReducer默認情況下跟蹤鉤子中的狀態,而不是實際單獨的 Redux 存盤。
請注意,您可以使用 RTKcreateSlice來創建專門用于useReducer掛鉤的減速器 - 減速器函式只是函式,并且在任何地方都可以正常作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/411276.html
標籤:
上一篇:Meteor全球版本與專案不同
