LoginSignup
1
2

More than 5 years have passed since last update.

Reduxまとめ

Last updated at Posted at 2018-01-31

Redux

Action編

データの流れ
1. ActionCreatorActionを作成
2. Reducerが現在のstate, actionを元に新しいstateを作成
3. stateの変更をUIなどに反映

Action

Storestateを変更するためのメッセージ(オブジェクト)
ActionCreatorによって作成されるオブジェクトのため、実体として定義はされない

{
    type: "SHOW_ERROR",
    error: message
}

ActionCreator

Actionを返す単純な関数
ComponentReducerを繋ぐ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

Componentstate, actionstore.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

connectActionCreatorをマッピングする際、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);
1
2
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
2