LoginSignup
0
0

More than 5 years have passed since last update.

Redux 勉強会に参加してきた

Posted at

first chapter -概要-

前回のReact勉強会に参加させて頂いた会の続きで、Reduxの会に参加させて頂いたので記憶が消えない今日のうちにメモ。φ(・

 chapter01 - Reduxとreact-redux

  • Reduxとreact-reduxは別物、分けて考えたほうが整理できる
  • Reduxは状態管理ツール。Reactと一緒に使用することも、他のビューライブラリと一緒に使用することもできる。
  • react-reduxは、ReactでReduxを使うためのライブラリ。

 chapter02 - なぜReactにReduxか -

  • propsバケツリレーを解消できる
  • どのコンポーネントからでもstateと更新するハンドラを読み込むことができる

chapter03 - Reduxの基礎 -

store

  • 状態管理場所。Reduxではstoreで全ての状態管理を行う。
  • reducerを引数にcreateStore()メソッドを実行しstoreを作る。
const store = redux.createStore(reducer);

reducer

  • storeを更新する際に使用する。storeは神聖なものなのでreducerという門番を通さずには更新できない。
  • Reduxには変更は純粋な関数から行われるべきという原則がある。
  • actionに応じて新しいstoreを返す関数
const reducer = (state=initialState, action) => {
  switch(action.type){
    case: "COUNT_UP":
      return {...state, count: state.count + 1 };
    default:  // defaultを忘れずに書かないと、初期ロードでつまづきやすい
      return {...state, state };
  }
};

action

  • storeに対し、どのような変更をしてほしいか書かれたメッセージ。
  • {type: string, payload?: mixed} 形式のただのオブジェクト
  • typeは様々なアクションの識別子、payloadは更新してほしいデータ。
  • store.dispach(action)でreducerを実行し、actionを元にstoreを更新できる。
store.dispach({type: "COUNT_UP"});

chapter04 - react-reduxの基礎 -

provider(react-reduxが持つ機能)

  • で囲ったコンポーネント配下は、reduxのstoreにアクセスできるようになる。
  • ルートコンポーネントに記述すればおk
ReactDOM.render(
 <Provider store={store}>
  <App />
 </Provider>, document.getElementById("root")
);

connect(react-reduxが持つ機能)

  • コンポーネントとstoreを接続するための仕組み
connect(mapStateToProps, mapDispatchToProps)(Component);

mapStateToProps(自作する)

  • storeのどの値をコンポーネントで使用したいかを選択する機能。
// state => stateでもいいが、不必要な値は入れないほうがいい
const mapStateToProps = state => ({ value: state.value })

mapDispatchToProps(自作する)

  • どのactionをdispatchさせるのか定義する
  • 通常アクションの生成からdispatchの実行まで行う関数を定義し、propsに渡す
const mapDispatchToProps = dispatch => { 
  dispatchAddValue: amount => dispatch(addValue(amount)) 
};

actionCreator(自作する)

  • actionを作る関数
  • 呼ぶだけでactionを作るように自分で定義する
const checkUser = (userId) => {
  return { type: CHECK_USER, payload: id };
};

Last chapter

感想
最初覚えられない!!!って思ったんだけど
手を動かすことで勝手になんとなく覚えてきました。
習うより慣れろですね。
でも、仕組みとか引数とか型とか
一応なんとなくでもどういうものかって
理解しないとこわいから

理解する->覚える->手を動かして慣れる->復習する

っていうのが一番効率いいかなって思いました。

0
0
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
0