使用 Redux 工具包连接 Redux 商店

时间:2021-07-12 06:09:20

标签: javascript reactjs redux store redux-toolkit

出于各种原因,我的工作场所目前正在尝试将 React/Redux 引入我们的项目。我们的项目使用 Shopify 和 Liquid 模板以及 jQuery。他们想向 React 迁移,到目前为止,我们一直通过寻找特定 ID 并以这种方式注入 React 组件来注入 React。

由于这个原因,并且因为我们现在需要一个存储来保存和呈现数据,我遇到了一个奇怪的问题。如果我用 Provider 和 store 包装这些注入的组件中的每一个,我基本上可以让每个组件都有自己的 store,但这根本无济于事,因为它几乎模仿了本地状态。

有没有办法让我“连接”并与多个组件共享商店?

我想过包装整个项目,通常情况下,但这样做会/应该使液体无用。

这是正在发生的事情的示例:

import ReactDOM from "react-dom";
import React from "react";

import attrToProps from "../../../partials/data-attribute-to-props.js";
import FavoritesToggler from "./index.js";
import store from "./../../Store/store"
import { Provider } from "react-redux"

const rootEl = document.getElementById("fav-container-react");

if(rootEl) {
    const props = attrToProps(rootEl.attributes);
    rootEl && ReactDOM.render(<Provider store={store}><FavoritesToggler {...props} /></Provider>, rootEl);
}

这被注入到一个包含 'fav-container-react' id 的 div 中。

但我们目前有几个这样的,我想知道如何让它们连接到同一个商店。

如果有任何想法,我们将不胜感激,包括可能的架构变化(我们需要“展示进展”才能继续获得资助,因此不能选择开始一个新项目。这意味着我需要一个解决方案能够不断将遗留代码更新为 React)

1 个答案:

答案 0 :(得分:0)

如果组件有 store 属性并且您使用 connect,则不需要提供程序。 hooks 不起作用,因此我建议使用可以在所有项目都转换为 React 时使用钩子重构的容器。

const { connect } = ReactRedux;
const { createStore, applyMiddleware, compose } = Redux;

const initialState = { counter: 0 };
//action types
const UP = 'UP';
//action creators
const up = () => ({
  type: UP,
});
const reducer = (state, { type }) => {
  if (type === UP) {
    return { ...state, counter: state.counter + 1 };
  }
  return state;
};
//selectors
const selectCounter = (state) => state.counter;
//creating store with redux dev tools
const composeEnhancers =
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
  reducer,
  initialState,
  composeEnhancers(
    applyMiddleware(
      () => (next) => (action) => next(action)
    )
  )
);
const App = ({ count, up }) => {
  return <button onClick={up}>{count}</button>;
};
const AppContainer = connect(
  (state) => ({
    count: selectCounter(state),
  }),
  { up }
)(App);

const OtherContainer = connect(
  (state) => ({
    count: selectCounter(state),
  })
)(({count})=><h1>{count}</h1>);

ReactDOM.render(
  <AppContainer store={store} />,
  document.getElementById('root-1')
);
ReactDOM.render(
  <AppContainer store={store} />,
  document.getElementById('root-2')
);
ReactDOM.render(
  <OtherContainer store={store} />,
  document.getElementById('root-3')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.0/react-redux.min.js"></script>

<div id="root-1"></div>
<div id="root-2"></div>
<div id="root-3"></div>