Skip to main content

React TS - useReducer Type

使用 useReducer 管理狀態

useReducer 是 React 中勇於處理複雜狀態邏輯的 hook,它接受一個 reducer 函式和一個初始狀態,並回傳當前狀態和 dispatch 函式。Reducer 函式是一個接受當前狀態和操作(action)的函式,它會根據不同操作來更新狀態。

// 定義 actions
interface CounterAction {
type: "increment" | "decrement" | "reset";
}

interface UpdateDraftCounterAction {
type: "updateDraftCount";
payload: number | string;
}

type InitialState = {
count: number;
draftCount: string | number;
};

const initialState: InitialState = {
count: 0,
draftCount: 0,
};

// 這個reducer函式接受4種不同 type 的 action
const reducer = (
state = initialState,
action: CounterAction | UpdateDraftCounterAction
) => {
let { count, draftCount } = state;

switch (action.type) {
case "increment":
count = count + 1;
return { count: count, draftCount: count };
case "decrement":
count = count - 1;
return { count: count, draftCount: count };
case "reset":
return { count: 0, draftCount: 0 };
case "updateDraftCount":
return { count, draftCount: action.payload };
}

return state;
};

將 dispatch 作為參數傳遞

為了讓子元件能夠觸發狀態更新操作,可以將 dispatch 函式作為子元件的 props 傳遞

import React, { Dispatch } from "react";

type UpdateHexColorAction = {
type: "update-hex-color";
payload: {
hexColor: string;
};
};

type UpdateRGBColorAction = {
type: "update-rgb-color";
payload: { rgb: [r: number, g: number, b: number] };
};

type ColorState = {
hexColor: string;
};

type ColorActions = UpdateHexColorAction | UpdateRGBColorAction;

type AdjustColorsProps = {
hexColor: string;
dispatch: Dispatch<ColorActions>;
};

const colorReducer = (
state: ColorState,
action: UpdateHexColorAction | UpdateRGBColorAction
) => {
if (action.type === "update-hex-color") {
const { hexColor } = action.payload;
return { ...state, hexColor };
}

if (action.type === "update-rgb-color") {
const hexColor = rgb.hex(action.payload.rgb);
return { ...state, hexColor };
}

return state;
};

const AdjustColors = ({ hexColor, dispatch }: AdjustColorsProps) => {
return <div>{hexColor}</div>;
};

參考資料