0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【redux-actions】Typescriptでの実装方法メモ

0
Posted at

概要

react-native製アプリで、redux-actionsを導入しているがTypescript向けの実装サンプルがあまり見つからなかったので備忘として。
countという数値型の変数を持つstateに下記2種のActionを定義した場合の例です。

  • payloadの値をcountに加算するadd
  • meta.hogetrueならpayloadcountに乗算するmulti

ポイントはmultiの方で、metaを絡めた場合のActionの定義の方法がちょっと分かりにくかった印象でした。

動作環境

関係してそうなライブラリのみ記載しています。

  • typescript @3.5.2
  • react-native @0.59.9
  • redux @4.0.1
  • redux-actions @2.6.5
  • @types/redux-actions @2.6.1

インストール

npm install --save redux-actions 
npm install --save @types/redux-actions

実装

import { 
    createActions, 
    handleActions, 
    Action,
    ActionMeta 
} from 'redux-actions';

// State定義
class InitialState  { 
    count : number = 1;
};

// Stateインスタンス作成
const initialState : InitialState = new InitialState();

// Action定義
const { add, multi } = createActions({
  // payloadのみのAction
  add : (value : number) => value,
  // payload + metaのAction
  multi: [(value : number) => value, (value : number, meta : { hoge : boolean }) => meta],
});

// Reducerの定義
const reducer = handleActions(
  {
    // payloadのみの場合はAction<payloadの型>
    add : (state : { count : number }, action : Action<number>) => ({
        ...state,
        count : state.count + action.payload,
    }),
    // metaがある場合はActionMeta<payloadの型, metaの型>
    multi : (state : { count : number }, action : ActionMeta<number, { hoge : boolean}>) => ({
        ...state,
        count : action.meta.hoge? state.count * action.payload : state.count,
    }),
  },
  initialState 
);
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?