React Redux Redux-Toolkit

[Redux #3] Redux-Toolkit(RTK) & Redux thunk

許馨方 Mia Hsu 2022/10/12 16:13:03
1575

在上一篇我們手動建立了 Redux 的相關內容後,對於 React 與 Redux 的串接有了基本的概念。

我們可以接著使用官網提供的 Template 來進行實作,此篇將會說明當中相關的 fuctoin 的用途及操作方法。

為什麼會有 Redux-Toolkit?

最主要的原因在於:

減少 Boilerplate(樣板)

要寫 Redux 時會需要建置許多的 boilerplate,建置 Store、Action、Action Type、Reducers….等,建置這些檔案很麻煩又費時,因此 Redux-Toolkit 提供了更簡潔的語法,讓工程師可以比較輕鬆的使用 Redux。

使用官網提供的 Template

npx create-react-app redux-essentials-example --template redux
運行畫面
file tree

可以看到專案裡直接提供 Redux 的 boilerplate,並使用 Counter 做一個小範例,以下會直接以檔案進行說明。

  • src/index.js:直接寫好 Provider
index.js
  • src/features/counter/Counter.js:一樣使用到 useSelector 及 useDispatch
  • src/store.js:使用 configureStore 創建 store
  • src/features/counter/counterSlice.js: slice 指的是將許多的 Reducer 或 actions 集合起來,因此這隻檔案就包含了 initialState、Actions、Reducers、ActionType 等內容。

 

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import { fetchCount } from './counterAPI';

const initialState = {
  value: 0,
  status: 'idle',
};

// The function below is called a thunk and allows us to perform async logic. It
// can be dispatched like a regular action: `dispatch(incrementAsync(10))`. This
// will call the thunk with the `dispatch` function as the first argument. Async
// code can then be executed and other actions can be dispatched. Thunks are
// typically used to make async requests.
export const incrementAsync = createAsyncThunk(
  'counter/fetchCount',
  async (amount) => {
    const response = await fetchCount(amount);
    // The value we return becomes the `fulfilled` action payload
    return response.data;
  }
);

// 整合了 reducer、action、actionType
export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  // 定義 reducers 及相關操作
  reducers: {
    // 根據名稱自動產生 action
    increment: (state) => {
      // 使用了 Immer 套件,讓原本 immutable 的 state 變為 mutative (不是真的 mutative 只是套件做了轉換)
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    // 使用 action.payload 取得值
    incrementByAmount: (state, action) => {
      state.value += action.payload;
    },
  },
  // The `extraReducers` field lets the slice handle actions defined elsewhere,
  // including actions generated by createAsyncThunk or in other slices.
  extraReducers: (builder) => {
    builder
      .addCase(incrementAsync.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(incrementAsync.fulfilled, (state, action) => {
        state.status = 'idle';
        state.value += action.payload;
      });
  },
});

// 取得 Action,也等於 ActionType
export const { increment, decrement, incrementByAmount } = counterSlice.actions;

// The function below is called a selector and allows us to select a value from
// the state. Selectors can also be defined inline where they're used instead of
// in the slice file. For example: `useSelector((state: RootState) => state.counter.value)`
export const selectCount = (state) => state.counter.value;

// We can also write thunks by hand, which may contain both sync and async logic.
// Here's an example of conditionally dispatching actions based on current state.
export const incrementIfOdd = (amount) => (dispatch, getState) => {
  const currentValue = selectCount(getState());
  if (currentValue % 2 === 1) {
    dispatch(incrementByAmount(amount));
  }
};

export default counterSlice.reducer;

 

檔案裡面好像還有其他部分….?

要理解剩餘的部分,需要先了解什麼是「middleware」

  • 後端中的 middleware:middleware 可以說是一種封裝的功能,是指從發出 HTTP 請求後,到應用程式接收回應前,用來處理特定用途的程式,比如說身份驗證、啟用路由等。
圖片來源: https://ithelp.ithome.com.tw/articles/10259251
  • Redux 中的 middleware:處理 action 傳遞到 store 之前的操作,像是一個 action 轉換,常常會在這邊處理非同步的操作。

常用的 Redux Middleware 套件

  • Redux-thnuk
  • Redux-saga
  • Redux-observable

三個都是用來處理非同步的操作,其中 「redux-thnuk」被包含於 redux-RTK 中,以下將介紹 Redux-thnuk 此 middleware。

Redux-thnuk

簡單說就是一個 Function,原本的 action 會是一個 javaScript object,但有了 Redux-thnuk 之後,Action 就可以是一個 Function,如此一來我們就可以在這個 Function 裡面執行非同步的操作。

createAsyncThunk()

是 RTK 提供的一個創建 Redux-thunk 並簡化開發者要撰寫isLoadingerror  data 繁瑣的過程。 

 

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import { fetchCount } from './counterAPI';

// 創建 Redux-thunk 並簡化開發者要撰寫isLoading、error 和 data 繁瑣的過程,的一個 Function
export const incrementAsync = createAsyncThunk(
  // type
  'counter/fetchCount',

  // payloadCreator(arg, thunkAPI)
  async (amount, thunkAPI) => {
    const { dispatch, getState, extra, requestId, signal, rejectWithValue, fulfillWithValue } = thunkAPI;
    const response = await fetchCount(amount);
    // The value we return becomes the `fulfilled` action payload
    return response.data;
  }
);

incrementAsync.pending();     // 'counter/fetchCount/pending'
incrementAsync.fulfilled();   // 'counter/fetchCount/fulfilled'
incrementAsync.rejected();    // 'counter/fetchCount/rejected'
  • createAsyncThunk 會根據 type 自動產生出三個對應的 action function :pending()fulfilled()rejected()
  • thunk 會在執行 payload creator 之前 dispatch pending(),接著根據 Promise 變成對應的 fulfilled()rejected()

如何使用 pending()fulfilled()rejected()

由於這幾個 Action 並不是在 Slice 中被定義,所以如果要監聽這三個 Type,需要在 extraReducers 中透過 builder.addCase 來使用

 
// 整合了 reducer、action、actionType
export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  // 定義 reducers 及相關操作
  reducers: {
    // 根據名稱自動產生 action
    increment: (state) => {
      // 使用了 Immer 套件,讓原本 immutable 的 state 變為 mutative (不是真的 mutative 只是套件做了轉換)
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    // 使用 action.payload 取得值
    incrementByAmount: (state, action) => {
      state.value += action.payload;
    },
  },
  // 由於 AsyncThunk 這些 action 並不是在 slice 中被定義,
  // 所以如果要在 createSlice 中監聽這些 action type,需要在 extraReducers 中透過 builder.addCase 來使用。
  extraReducers: (builder) => {
    builder
      .addCase(incrementAsync.pending, (state) => {
        console.log(state.status);
        state.status = 'loading';
      })
      .addCase(incrementAsync.fulfilled, (state, action) => {
        console.log(state.status);
        state.status = 'idle';
        state.value += action.payload;
      });
  },
});

 

重點筆記

  • Redux-Toolkit(RTK)解決了 Redux 大量 boilerplate 的問題,提供 Redux 配置模板。
  • slice:指的是將許多的 Reducer 或 actions 集合起來。
  • createSlice():整合了 reducer、action、actionType。
  • Immer:是一個套件,讓原本 immutable 的 state 變為 mutative (不是真的 mutative 只是套件做了轉換)。
  • Redux 中的 middleware:處理 action 傳遞到 store 之前的操作,像是轉換 action,常常會在這邊處理非同步的操作。
  • createAsyncThunk():是 RTK 提供的一個創建 Redux-thunk 並簡化開發者要撰寫isLoadingerror 和 data 繁瑣的過程。

參考資料

 

 

 

許馨方 Mia Hsu