Skip to content

Instantly share code, notes, and snippets.

@nishinoshake
Last active June 19, 2016 06:22
Show Gist options
  • Save nishinoshake/71a05b914c2427cb0accf2172df753a4 to your computer and use it in GitHub Desktop.
Save nishinoshake/71a05b914c2427cb0accf2172df753a4 to your computer and use it in GitHub Desktop.
Reduxがわからん

##Reduxとは Stateの管理をしてくれるライブラリ。
Reactと相性がいい。

##用語の整理 ###View 表示されるところ。DOM。

###Action 文字通りアクション。
厳密にはアクションを規定するオブジェクト。 新規作成したり変更したり削除したり。

###Action Cerator Actionのオブジェクトを作るやつ

###Reducer アクションをもとに新しいStateを作るやつ。

##処理の流れ ###Viewで何かイベント発生 クリックとかインプットとか

###Actionが呼ばれてReducerへ渡す dispatch(ActionCreator())とするとアクションを生成して、
Reducerを呼び出す。

###ReducerでActionを判別して新しいStateを生成 ReducerでActionのタイプを判別して、
それに従った処理をする。
Stateは上書きするのではなく、新しく作りなおす。

###変更されたStateがViewに反映される

import React, {PropTypes} from 'react'
import { render } from 'react-dom'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import { connect } from 'react-redux'
// Action Creator
function increment() {
return {
type: 'INCREMENT'
}
}
const initialState = {
now: 0
}
// Reducer
function incrementReducer(state, action) {
if ( !state ) {
return initialState
}
switch (action.type) {
case 'INCREMENT':
return {
now: state.now + 1
}
}
}
// Container
const mapStateToProps = (state, ownProps) => {
return {
now: state.now
}
}
const mapDispatchToProps = (dispatch) => {
return {
handleClick: () => { dispatch(increment()) }
}
}
let App = (({now, handleClick}) => {
return (
<div>
<p onClick={() => handleClick()}>
{now}
</p>
</div>
)
})
// ReduxのStateとReactのPropsを結びつける
App = connect(
mapStateToProps,
mapDispatchToProps
)(App)
let store = createStore(incrementReducer)
render(
<Provider store={store}>
<div>
<App />
</div>
</Provider>
, document.getElementById('root'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment