4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

AtraeAdvent Calendar 2019

Day 25

Reduxで1つのstoreを2つのrenderで共有する

Posted at

例えば既存のサイトに、部分的にReact/Reduxを導入したい場合、さらにはUI的にあちこちにコンポーネントが点在している場合(ボタン押してモーダル出すとか)、どう作るか?

答えは単純に複数回renderして同じstoreを渡せばいい
(ググってもサンプルが出てこなかったので残しておきます。どうってことない内容ですが...)

HogeAndFugaApp.js.jsx
import React from "react";
import ReactDOM from "react-dom";
import { connect, Provider } from "react-redux";
import { bindActionCreators, createStore, applyMiddleware } from "redux";
import createSagaMiddleware from "redux-saga";
import { createLogger } from "redux-logger";
import reducer from "./reducers";
import { commonAction } from "./actions";
import HogeComponent from "component/HogeComponent";
import FugaComponent from "component/FugaComponent";

/*globals process */
const logger = [];
if (process.env.NODE_ENV === "development") logger.push(createLogger());

const configureStore = () => {
  const sagaMiddleware = createSagaMiddleware();
  const store = createStore(
    reducer,
    applyMiddleware(sagaMiddleware, ...logger)
  );
  sagaMiddleware.run(rootSaga);
  return store;
};
const store = configureStore();

const mapStateToProps = (state) => ({
  commonProps: state.common,
});
const mapDispatchToProps = (dispatch) => ({
  commonAction: bindActionCreators(commonAction,dispatch)
});


const HogeApp = connect(mapStateToProps,mapDispatchToProps)(HogeComponent);

ReactDOM.render(
  <Provider store={store}>
    <HogeApp/>
  </Provider>,
  document.querySelector("#js-hoge")
);

const FugaApp = connect(mapStateToProps,mapDispatchToProps)(FugaComponent);

ReactDOM.render(
  <Provider store={store}>
    <FugaApp/>
  </Provider>,
  document.querySelector("#js-fuga")
);

だらだら1ファイルで書いてしまいましたが、要はHogeAppFugaAppで同じstoreを参照し、それぞれdocument.querySelector()でrenderしてるだけです。
同じcomponentを複数回renderするならArray.from(document.querySelectorAll("targetDom"))でeach回してrender出来るはずです。

誰かの参考になればm(__)m

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?