Redux
Action編
データの流れ
1. ActionCreator
でAction
を作成
2. Reducer
が現在のstate, action
を元に新しいstate
を作成
3. state
の変更をUIなどに反映
Action
Store
のstate
を変更するためのメッセージ(オブジェクト)
ActionCreator
によって作成されるオブジェクトのため、実体として定義はされない
{
type: "SHOW_ERROR",
error: message
}
ActionCreator
Action
を返す単純な関数
Component
とReducer
を繋ぐI/F的な役割
actions.js
export const SHOW_ERROR_MESSAGE = 'SHOW_ERROR_MESSAGE';
export function showErrorMessage(message) {
return {
type: SHOW_ERROR_MESSAGE,
error: message
}
}
Reducer
state, action
を元に新しいstate
を返す
state
を更新するためのロジックが定義される
reducer.js
function errorMessage(state = null, action) {
const { type, error } = action;
switch (type) {
case ActionTypes.SHOW_ERROR_MESSAGE:
return error;
case ActionTypes.RESET_ERROR_MESSAGE:
return null;
default:
return state;
}
}
Connect
Component
にstate, action
をstore.props
としてアクセス出来るようマッピングしてくれる
// ActionCreator
import actions as actions from '../actions';
class Container extend Component {
handleShowError(e) {
const { showErrorMessage } = actions;
e.preventDefault();
this.props.dispatch(
showErrorMessage('エラーだよ')
);
}
render() {
return (
<button onClick={this.handleShowError}>ボタン</button>
);
}
}
// Storeのstateをstore.propsとして返す
const mapStateToProps = state => ({
return state;
});
export default connect(
// state => store.props
mapState
// ActionCreator
{ ...actions }
)(Container);
bindActionCreators
connect
にActionCreator
をマッピングする際、dispatch
関数にActionCreator
をバインドしたプロパティとして展開してくれる
(つまり、dispatch
する手間を省いてくれる)
下記のコードを抽象化してくれる
function mapDispatchToProps(dispatch) {
return {
// actionXをdispatchするhandleClickプロパティを展開
handleClick: () => {
dispatch(actionCreatorX())
}
}
}
// ActionCreator
import actions as actions from '../actions';
class Container extend Component {
render() {
return (
<button onClick={this.props.showErrorMessage('エラーだよ')}>ボタン</button>
);
}
}
// Storeのstateをstore.propsとして返す
const mapState = state => ({
return state;
});
// dispatch関数がバインドされたActionCreatorを返す
function mapDispatch(dispatch) {
return {
actions: bindActionCreators(actions, dispatch)
}
}
// Containerにマッピング
export default connect(
mapState
mapDispatch
)(Container);