LoginSignup
1
6

More than 5 years have passed since last update.

React Reduxでコンポーネント間の値共有を行う場合のメモ

Posted at

概要

新年早々にReact Reduxを試してみたいと思い立ち、いろいろ調べる中でふとコンポーネント間の値共有ってどうやるんだろうと思って作ってみたサンプルのメモです。なお、React Reduxの仕組み等々については@erukitiさんの記事React+Redux入門や書籍 React入門 React・Reduxの導入からサーバサイドレンダリングによるUXの向上までを参考にするとよいと思います。

例題

下記のようにテキストボックスに入力するコンポーネント、入力した内容を表示するコンポーネントで分けたときに値の共有を行うサンプルを記載します。
image.png

サンプルソース

index.js

InputAppが入力部分、ViewAppが表示部分になります。

index.js
import React from 'react';
import {Provider} from 'react-redux';
import {createStore} from 'redux';
import {render} from 'react-dom';
import inputReducer from './reducers/input';
import InputApp from './containers/InputApp';
import ViewApp from './containers/ViewApp';

const store = createStore(inputReducer);

render( 
  <Provider store ={store}>
    <InputApp />
    <ViewApp />
  </Provider >,
  document.getElementById('root')
);

containers

InputApp.js
import {connect} from 'react-redux';
import InputApp from '../components/InputApp';
import {inputName} from '../actions/input';

function mapStateToProps({name}) {
  return {name};
}

function mapDispatchToProps(dispatch) {
  return {
    inputName(name) { dispatch(inputName(name)); }
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(InputApp);

ViewApp.js
import {connect} from 'react-redux';
import ViewApp from '../components/ViewApp';

function mapStateToProps({name}) {
  return {name};
}

export default connect(mapStateToProps)(ViewApp);

components

InputApp.js
import React from 'react';

export default function InputApp({name, inputName}){
  return (
   <div>
    名前
       <input type ="text" onChange = {(e) => inputName(e.target.value)} />
   </div>
  );
}

ViewApp.js
import React from 'react';

export default function ViewApp({name}){
  return (
    <div>
    名前{name}
    </div>
  );
}

actions

input.js
export const inputName = (name) => (
  { type: 'INPUT_NAME', payload: {name} }
);

reducers

input.js
const initialState = { name: ''};

export default function inputReducer(state = initialState, action) {
  switch (action.type) {
    case 'INPUT_NAME':
     return { ...state, name: action.payload.name};
    default:
     return state;
  }
}
1
6
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
1
6