问题描述
我有一个使用 redux 来实现的 react 应用程序。在使用 redux 之前,我能够成功将其发布为 npm 包库,并将其用作另一个 react 应用程序中的第三方组件。 然后我使用 redux 进行实现,并在更改版本后通过简单地运行“npm publish”再次发布它。我能够成功发布它。 但是当我在另一个不使用 redux 的 React 应用程序中将它用作第三方组件时,它给了我一个错误。
有没有什么办法可以发布一个使用 react-redux 的包,作为第三方组件在不使用 redux 的 React 应用中使用?
Error: Could not find react-redux context value; please ensure the component is wrapped in a <Provider>
▶ 21 stack frames were collapsed.
Module.<anonymous>
D:/test/my-app/src/index.js:7
4 | import App from './App';
5 | import reportWebVitals from './reportWebVitals';
6 |
> 7 | ReactDOM.render(
8 | <React.StrictMode>
9 | <App />
10 | </React.StrictMode>,
解决方法
您可以使用 custom context 来防止您的包的 redux 存储与可能已经存在的 redux 存储发生冲突。在这种情况下,您将导出您自己的 Provider
组件,该组件创建并传递了一个 redux 存储,并且您的包的使用者需要将该提供程序包装在他们的应用程序中。