返回

React useReducer + Context 在 TS 中更友好的使用方式

前端

在 React 项目中,我们经常需要在组件之间共享状态。其中一种常用的方式是使用 useReducer + Context。但是,在 TypeScript 中使用 useReducer + Context 可能会遇到一些问题。本文将介绍如何更友好的使用 useReducer + Context。

问题

在 TypeScript 中使用 useReducer + Context 时,可能会遇到以下问题:

  • 类型推断不准确 。useReducer 和 useContext 的类型推断不准确,可能会导致类型错误。
  • 默认值不友好 。useReducer 和 createContext 的默认值不友好,可能会导致错误。

解决方法

为了解决这些问题,我们可以使用以下方法:

  • 使用类型别名 。我们可以使用类型别名来指定 useReducer 和 useContext 的类型,从而提高类型推断的准确性。
  • 使用自定义 Hook 。我们可以使用自定义 Hook 来封装 useReducer 和 createContext,从而简化代码并提高可读性。

使用示例

以下是一个使用类型别名和自定义 Hook 来更友好的使用 useReducer + Context 的示例:

// 定义类型别名
type State = {
  count: number;
};

type Action = {
  type: 'increment' | 'decrement';
};

// 定义自定义 Hook
const useGlobalState = () => {
  const [state, dispatch] = useReducer<Reducer<State, Action>>((state, action) => {
    switch (action.type) {
      case 'increment':
        return { ...state, count: state.count + 1 };
      case 'decrement':
        return { ...state, count: state.count - 1 };
      default:
        throw new Error('Unknown action type');
    }
  }, { count: 0 });

  return { state, dispatch };
};

// 使用自定义 Hook
const App = () => {
  const { state, dispatch } = useGlobalState();

  return (
    <div>
      <h1>Count: {state.count}</h1>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </div>
  );
};

总结

通过使用类型别名和自定义 Hook,我们可以更友好的使用 useReducer + Context。这可以提高类型推断的准确性,简化代码并提高可读性。