LoginSignup
183
112

More than 5 years have passed since last update.

Redux入門 2日目 Reduxの基本・Actions(公式ドキュメント和訳)

Last updated at Posted at 2015-11-22

前回 Redux入門 1日目 Reduxとは

前回に引き続き、reduxの公式ドキュメントを辿りながら、ざっくり和訳していきます。
2章からはTodoアプリを作成しながらReduxのそれぞれの要素を順番に解説していきます。

2.1 Actions

  • actionはアプリケーションからの情報をstoreへ送る為のオブジェクト
  • actionは store.dispatch()でstoreへ送られます
  • actionは、何を行なうものかを識別するために"type"プロパティを必ず持つ。他のプロパティについては自由。
const ADD_TODO = 'ADD_TODO'
{
  type: ADD_TODO,
  text: 'Build my first Redux app'
}
  • typeの値は文字列。アプリケーションが大きくなる場合は、typeの定義値を別モジュールにするとよい
import { ADD_TODO, REMOVE_TODO } from '../actionTypes'
  • 下記はTODOが終わったことを伝えるアクション。どのアイテムを参照するかをindexに記載してます。実際にはユニークなIDを発行して使用するのがいいでしょう
{
  type: COMPLETE_TODO,
  index: 5
}
  • 下記は表示モードを切り替えるactionです
{
  type: SET_VISIBILITY_FILTER,
  filter: SHOW_COMPLETED
}

Action Creators

action creatorsは、その名の通りactionを生成するメソッドです。

  • Fluxでは、action creator内でactionを作成して、そのままdispatchまでを行なうのが一般的です
function addTodoWithDispatch(text) {
  const action = {
    type: ADD_TODO,
    text
  }
  dispatch(action)
}
  • 対してReduxでは、シンプルにactionを作るだけです。その方がテストしやすいからです。
function addTodo(text) {
  return {
    type: ADD_TODO,
    text
  }
}
  • dispatchするときはcreatorで作成したactionを渡します。
dispatch(addTodo(text))
dispatch(completeTodo(index))
  • または、bound action creator としてdispatchまでを行なうcreatorを別途用意します
const boundAddTodo = (text) => dispatch(addTodo(text))
const boundCompleteTodo = (index) => dispatch(completeTodo(index))
  • react-reduxライブラリのconnectをimportして、ヘルパーのbindActionCreators()を使うのもいいでしょう
import { Component } from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'

let boundActionCreators = bindActionCreators(TodoActionCreators, dispatch)

続き Redux入門 3日目 Reduxの基本・Reducers

183
112
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
183
112