windsuzu / react-redux-demo

A simple [synchronous/asynchronous] example of using redux in react, which contains reactjs/toolkit and react-redux.

Home Page:https://windsuzu.github.io/react-redux-demo/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Contributors MIT License Author LinkedIn


React Redux Demo

A simple example of using redux in react, which contains reduxjs/toolkit and react-redux.
View Demo · Report Bug · Request Feature

Table of Contents

About

這個專案為 redux 的應用展示,使用兩個三方庫: @reduxjs/toolkit 以及 react-redux 來開發 redux 的主要功能。 專案中分別利用 redux 實作了同步 (synchronous) 與非同步 (asynchronous) 的實際狀況。

✨ 同步狀況

  • 例如: 本地的狀態改變不需要網路操作 (request/response)
  • 實作內容:
    • createSlice, configureStore from @reduxjs/toolkit
    • Provider, useSelector, useDispatch from react-redux

💫 非同步狀況

  • 例如: 需要網路操作載入資料庫資料 (fetch)上傳資料到資料庫 (send request)網路操作後更新 UI 元件
  • 實作內容:
    • 上傳
      • 利用 useEffect 監控本地端已更新好的資料,並上傳同步伺服器
    • 下載、更新 UI 介面 (有三種作法)
      1. components 中處理獲得資料後的 dispatch
      2. 自製 Action Creator Thunk 處理 dispatch
      3. 使用 @reduxjs/toolkit 提供的 createAsyncThunk

Built With

  • HTML5, CSS3, Javascript ES6
  • React.js + Redux
  • @redux.js/toolkit
  • react-redux

[DEMO] : https://windsuzu.github.io/react-redux-demo


Examples

✨ Synchronous Events

以 UI 的 toggle shoppingCart 功能為例,開發時照著以下步驟導入 redux

  1. createSlice
  2. configureStore
  3. Provider
  4. [useSelector] [control JSX]
  5. useDispatch

💫 Asynchronous Events

以 fetchCartData, sendCartData 功能為例,開發時可以選用下列三種方式導入 redux

這個方法將所有的網路處理邏輯寫在 App Component 當中。把 slice / store 保持得很乾淨,只有簡單的 state 與 action 處理;但對網路的處理 (等待、失敗、成功) 都寫在 App Component,讓 App Component 變得很雜亂。

這個方法將網路處理邏輯分開寫在一個額外的檔案 cartAction 中,並且因為 thunk 的優點,可以繼續使用 dispatch 發送更新需求給 redux。 原本的 slice / store 完全沒改變,而且 App Component 變得很乾淨。

這個方法是 02-action-creator-thunk 的進階方法,使用 @redux/toolkit 的 createAsyncThunk網路處理邏輯slice / store 變得更清楚。 因為 createAsyncThunk 會自動產生每個 function 的 pendingfulfilledrejected 三個狀況,所以我們可以在 createSlice 中用 extraReducers 去操控每個 function 三個狀況需要改變的 state。

Preview

License

Distributed under the MIT License. See LICENSE for more information.

Contact

Reach out to the maintainer at one of the following places:

Acknowledgements

About

A simple [synchronous/asynchronous] example of using redux in react, which contains reactjs/toolkit and react-redux.

https://windsuzu.github.io/react-redux-demo/

License:MIT License


Languages

Language:JavaScript 69.0%Language:CSS 21.0%Language:HTML 10.0%