Reduxが難しかったのですが、1つのファイルにまとめてみるとすんなり理解できたので記載。
準備
まずはReactの環境構築。
$ npx create-react-app アプリ名
次にカレンドディレクトリに移動してreduxの導入。
$ npm install redux react-redux // npm→yarnでも可
コード
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {createStore} from 'redux';
// Action
const increment = () => {
return {
type: 'INCREMENT'
}
}
const decrement = () => {
return {
type: 'DECREMENT'
}
}
// Reducer
const counter = (state = 0, action) => {
switch(action.type){
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
}
}
let store = createStore(counter)
// Display it in the console
store.subscribe(() => console.log(store.getState()))
// Dispatch
store.dispatch(increment())
store.dispatch(decrement())
store.dispatch(increment())
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);