React + Redux + Typescriptを読み解く
React
チュートリアル
Redux
Reducer
- Reducer は現在の state と Action から、新しい state を生成します。
- Reducerには全てのアクションが送られるのでtypeで識別する。下記のtypeはそういう意味で使用される。
export interface AddTodoAction extends Action { type: TodoActionType.ADD; payload: AddTodoPayload; }
pyload
データを設定する。
export type AddTodoPayload = { // State更新に必要な情報.(todoを追加する時に必要な情報。今回はテキスト)
text: string;
};
Typescript
declare
変数の宣言に必要。
declare var x: number;
x = 30;
console.log(x);
引数の”?”
可変長のパラメータを表す。
function buildName(firstName: string, lastName?: string) {
if (lastName)
return firstName + " " + lastName;
else
return firstName;
}
let result1 = buildName("Bob"); // works correctly now
let result2 = buildName("Bob", "Adams", "Sr."); // error, too many parameters
let result3 = buildName("Bob", "Adams"); // ah, just right
type
interface
のエイリアス。 Props
、 State
には type
を使用するのがベター
type Props = OwnProps & InjectedProps & StoreProps
type OwnProps = {...}
type StoreProps = {...}
Interface vs Type alias in TypeScript 2.7 - Martin Hochel - Medium
union型(合併型)
複数の型を持たせる。
type Actions
= AddTodoAction
| ToggleTodoAction;
使い方は、引数に複数の型を許容できるようにする為。
export const reducer = (state: State = init(), action: Actions) => {
switch (action.type) {
// ここでなぜかスマートキャストみたいなことが起きる。すごい。のでAddTodoPayloadに明示的に変換しなくて良い。
case TodoActionType.ADD:
return createAddedState(state, action.payload)
case TodoActionType.TOGGLE:
return createToggledState(state, action.payload)
default:
return state;
}
};
Packages
@types/history
Sessionの管理を簡易化する
import { History } from 'history'
import { createBrowserHistory } from 'history'
export const history = createBrowserHistory()
connectRouter(history)
ReactTraining/history: Manage session history with JavaScript
react-router
path毎に表示するコンポーネントを切り替える
<Switch>
<Route exact path="/todo" component={TodoApp} />
<Route component={Top} />
</Switch>
redux-actions
Actionの書き方をすっきりさせる。
export const Actions = {
clickOne () {
return {
type: 'CLICK_ONE',
}
},
clickTwo (value) {
return {
type: 'CLICK_TWO',
payload: value,
}
},
}
ES2015
export default
一つしか宣言できない。呼び出し先では好きな変数名で宣言できる。
export default connect(mapStateToProps)(Sample);
import SampleContainer from './sampleContainer.tsx';
# or below:
# import SC from './sampleContainer.tsx';
Lambdaの複数の”=>”
パラメータを表している
const add = x => y => x + y
# or below:
# const add = (x, y) => x + y
ecmascript 6 - What do multiple arrow functions mean in javascript? - Stack Overflow
npm
dependenciesとdevDependenciesの違い
dependencies
プロジェクト実行時のみ必要なものだけインストールする
- インストール:
npm install --production
devDependencies
開発時に必要なものをインストール(dependencies + devDependencies) をインストールする
- インストール:
npm install
勉強メモ/npmの使い方(node.js=v0.11.16, npm=2.3.0, 2015-03時点) - Qiita