LoginSignup
0
1

More than 3 years have passed since last update.

Redux超入門【React】

Posted at

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')
);
0
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
0
1