前回Counterアプリケーションをつくりましたが、App.js
に詰め込みました。
今回はApp.js
を複数のファイルに分割します。
src/actions/counter.js
1 2 3 4 5 6 7 8 9
| export const INCREMENT = 'INCREMENT'; export const increment = () => ({ type: INCREMENT, });
export const DECREMENT = 'DECREMENT'; export const decrement = () => ({ type: DECREMENT, });
|
アクションのtypeを定数定義しています。これはReducerでインポートします。
src/components/Counter.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import React from 'react'; import { connect } from 'react-redux'; import { increment, decrement } from '../actions/counter';
const Counter = ({ count, increment, decrement }) => { return ( <div> Count: {count} <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> </div> ); };
const mapStateToProps = state => ({ count: state, });
const mapDispatchToProps = { increment, decrement };
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
|
前回はCounterConnectを定義してエクスポートしていましたが、このファイルでエクスポートしたいのが1つだけになったので、defaultでエクスポートしています。
src/reducers/counter.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import { INCREMENT, DECREMENT } from '../actions/counter';
const counter = (state = 0, action) => { switch (action.type) { case INCREMENT: return state + 1; case DECREMENT: return state - 1; default: return state; } };
export default counter;
|
アクションに定義した定数をインポートします。
また、こちらも同様にdefaultでエクスポートしています。
src/App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import React from 'react'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import './App.css'; import Counter from './components/Counter'; import counter from './reducers/counter';
const store = createStore(counter); const App = () => { return ( <Provider store={store}> <Counter /> </Provider> ); };
export default App;
|
Counterコンポーネントとcounter Reducerはデフォルトなので中括弧なしでインポートしてます。
以上です。