1
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 5 years have passed since last update.

reactのreducerとreduxの復習メモ

Last updated at Posted at 2019-01-07

環境はcodesandbox

まずcodesandbox最初の状態をコメントアウトする

// import React from "react";
// import ReactDOM from "react-dom";

// import "./styles.css";

// function App() {
//   return (
//     <div className="App">
//       <h1>Hello CodeSandbox</h1>
//       <h2>Start editing to see some magic happen!</h2>
//     </div>
//   );
// }

// const rootElement = document.getElementById("root");
// ReactDOM.render(<App />, rootElement);


//ここから追記
import { createStore } from "redux";

const reducer = (state = 0, action) => {
  switch (action.type) {
    case "PLUS_ONE":
      return state + 1;

    default:
      return state;
  }
};

const store = createStore(reducer);

console.log(store);

// subscribeとは、stateが変更されたときにこれを実行してください
store.subscribe(() => {
  // 自分自身のstateを表示してくれるgetState()
  console.log(store.getState());
});

// この上の状態だとアクションが発行されていないのでdispatch(発射)してアクションを発行する必要がある

// ここでtype "PLUS_ONE"というアクションを送ったのでreducerで受け取って一致しているものを返してくれる(つまり一致したstateを返す)
store.dispatch({
  type: "PLUS_ONE"
});

これでsubscribeによって(stateが変更されたときに実行される)1と表示される

そしてこの次にまた同じように

store.dispatch({
  type: "PLUS_ONE"
});

するとアクションが発行されるので2という数字が表示される

用語に慣れよう(個人的メモ)

reactを触る際、とにかく用語が出てくるので英語ができない私(頭のスペックが悪いので)にとっては用語を整理したほうが良いと感じた

一通り上の方でコメントしているが、そこを理解すればデータの流れを把握することができる

まとめ

react,redux特にプロジェクトになるとかなりコードを読み解けなくなる、、、が、基本をおさらいしてデータの流れをきちんとわかれば追いやすくなる(当然ですよね、まだまだスペック弱くてすみません)

イメージのまとめ

Component connected to store → action(dispatch) → reducer → new State → sotre → stateを上書き
1.storeを通してコンポーネントからアクションを発行
2.dispatch(reduxでいうとmapDispatchToProps)されてreducerに行く
3.reducerを通って処理が実行され、新しいstateを作る(newStateが作られる)
4.それがstoreの中のstateを上書きして新しくレンダリングされる

的なイメージ

1
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
1
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?