我想封装一个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 项目,并从 npm 导入 FileExplorer
组件
索引.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>
);
}
最佳答案
这里有几个想法。
第一个是肯定的,如果组件嵌套在 <FileExplorer>
中,这绝对会导致冲突还需要访问应用范围内的 Redux 存储,因为默认情况下所有连接 Redux 的 React 组件都通过 React 上下文访问同一个存储实例。
技术上可以将替代上下文传递给 <Provider>
并创建 useSelector/useDispatch
的自定义版本从该上下文中读取商店:
https://react-redux.js.org/using-react-redux/accessing-store#providing-custom-context
尽管看起来我们实际上并没有记录用于创建上下文定制版本的选择器 Hook 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
中跟踪状态hook 作为默认值而不是实际的单独 Redux 存储。
请注意,您可以使用 RTK 的 createSlice
创建一个专门用于 useReducer
的 reducer hook - reducer 函数只是函数,在任何地方都可以正常工作。
关于javascript - 来自 npm 的 React 组件中的 Redux 会与容器的 Redux 冲突吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70700049/