iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 13
3
Modern Web

TypeScript + React + 雜七雜八系列 第 13

【Day 13】Redux 與 React 與 TypeScript 之小小應用

大家好,今天的篇章要介紹的是 Redux + React + TypeScript

會延續前一天的專案結構接續下去進行修改,如果沒有參與到昨天的建置過程,這邊也有提供原始碼
https://github.com/littlehorseboy/typescript-react/tree/day12-typescript-redux


今天要把 React Router 篇章中登入驗證的程式碼給修改成 Redux 的版本

先調整一下 Root.tsx,為了昨天的文章而改成的部分,現在要把它改回來

要改成 redux 版本那就是得先新增 reducer 以及 action 了

+ src/reducers/login/login.ts
+ src/actions/login/login.ts

這邊用來紀錄登入後的狀態以及登入名稱

這邊定義 action,登入 login 及登出 logout

修改 configureStore.ts 將新的 loginReducer 加入

然後我就太衝動的想做一個 Header 並把連結跟登入功能通通放在裡面,也把排版跟顏色都調了調 XD

+ src/components/Header/Header.tsx

material-ui 的 Button 可以直接吃掉 Link 並使用他的屬性,這還蠻特別的,還蠻好奇怎麼自己做這種 component

然後是新增一個登入用的表單

+ src/components/Login/Login.tsx

修改 Router.tsx 以及 PrivateRoute.tsx

src/router/Router.tsx

src/router/PrivateRoute.tsx

再來就是 Router.tsx 裡面所引用到其它 component

+ src/components/Home/Home.tsx
+ src/components/day13/PrivateRoute/PrivateRoute.tsx

執行結果

這樣就有一個勉強還能看且可以亂放功能的 Header 啦!~


再來是做一個 loading (擋畫面用?)效果的 component,也是大量利用 material-ui 提供的 component 來實作,搭配 redux 的開關讓你不管到哪都可以切換顯示狀態

那就還是一步一步,先新增 action

+ src/actions/isLoading/isLoading.tsx

開啟是用 loading,關閉是用 loaded,然後新增 reducer

+ src/reducers/isLoading/isLoading.tsx

主要就是會去改變 isLoading 的 boolean 值

可別忘了還要將 reducer 給扔進 store

做個有特效的 component 啦~

+ src/reducers/isLoading/isLoading.tsx

完全都是用 material-ui 提供的 component,直接利用它的 Dialog 放進 CircularProgress,然後將 reducer 中的 isLoading 給掛上去準備做切換

然後在 Router.tsx 將 component 引進來

終於到了最後一步驟了,找個你想要驅動 isLoading 的任意 component,筆者選定了在 privateHome 之中

這邊是用 setTimeout 一秒來展示,不過平常筆者大多都是用在 ajax 請求的前後

執行結果


以上就是筆者在使用 typescript + Redux 的一點小小心得

最後附上原始碼
https://github.com/littlehorseboy/typescript-react/tree/day13-typescript-redux


這樣 redux 的篇章就算暫時結束了,不知道後面會不會想來寫 redux-observable,因為 RxJS 筆者認為也是一個蠻特別的東西,總是好奇怎麼寫能更有趣阿!明天要介紹 Formik,它是一個在 React 製作表單的利器!


上一篇
【Day 12】Redux 與 React 與 TypeScript
下一篇
【Day 14】Formik,在 React 製作表單的利器
系列文
TypeScript + React + 雜七雜八30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言