【React】尝试使用useReducer

使用 useReducer 进行状态管理

React Hooks 提供了一种很棒的工具,用于处理函数组件中的状态和生命周期。其中,useReducer 在复杂的状态管理方面尤其强大。本文将解释 useReducer 的基本用法。

1. 基础的 useReducer

useReducer是用于管理状态的函数。通常情况下,它用于在组件内管理复杂的状态或者更新逻辑复杂的情况。让我们来看看基本的用法。

import { Reducer } from "react";

interface State {
  count: number;
}

interface Action {
  type: "INCREMENT" | "DECREMENT";
}

const reducer: Reducer<State, Action> = (state, action) => {
  switch (action.type) {
    case "INCREMENT":
      return { count: state.count + 1 };
    case "DECREMENT":
      return { count: state.count - 1 };
    default:
      return state;
  }
};

export default reducer;
import React, { useReducer } from "react";
import reducer from "./Reducer";

const Counter: React.FC = () => {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: "INCREMENT" })}>Increment</button>
      <button onClick={() => dispatch({ type: "DECREMENT" })}>Decrement</button>
    </div>
  );
};

export default Counter;

2. 结合使用useReducer和Context

通过将 useReducer 与 Context 结合使用,可以实现全局状态管理。这样一来,多个组件可以引用相同的状态。

import { Reducer } from "react";

export interface State {
  count: number;
}

export interface Action {
  type: "INCREMENT" | "DECREMENT";
}

const reducer: Reducer<State, Action> = (state, action) => {
  switch (action.type) {
    case "INCREMENT":
      return { count: state.count + 1 };
    case "DECREMENT":
      return { count: state.count - 1 };
    default:
      return state;
  }
};

export default reducer;
import { ReactNode, createContext, useReducer } from "react";
import reducer, { Action, State } from "./Reducer";


interface CounterContextProps {
  state: State;
  dispatch: React.Dispatch<Action>;
}

export const CounterContext = createContext<CounterContextProps | undefined>(
  undefined
);

const initialState = { count: 0 };

const CounterProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <CounterContext.Provider value={{ state, dispatch }}>
      {children}
    </CounterContext.Provider>
  );
};

export default CounterProvider;
import React, { useContext } from "react";
import { CounterContext } from "./CounterProvider";

const CounterControls: React.FC = () => {
  const { dispatch } = useContext(CounterContext)!; // 非nullアサーション演算子

  return (
    <div>
      <button onClick={() => dispatch({ type: "INCREMENT" })}>Increment</button>
      <button onClick={() => dispatch({ type: "DECREMENT" })}>Decrement</button>
    </div>
  );
};

export default CounterControls;
import React, { useContext } from "react";
import { CounterContext } from "./CounterProvider";

const Counter: React.FC = () => {
  const { state, dispatch } = useContext(CounterContext)!; // 非nullアサーション演算子

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: "INCREMENT" })}>Increment</button>
      <button onClick={() => dispatch({ type: "DECREMENT" })}>Decrement</button>
    </div>
  );
};

export default Counter;

3. useReducer的优势是什么?

複雑な状態管理: useReducerは状態の複雑なロジックを分離しやすくします。これによりコンポーネントがより単純で理解しやすくなります。

グローバルな状態管理: Contextと組み合わせることで、グローバルな状態管理が容易になります。異なる階層のコンポーネントで同じ状態を使用する場合に便利です。

可読性と保守性: useReducerを使うことで、コンポーネントが持つロジックがより一貫していて、保守性が向上します。

4. 总结

useReducer是React应用程序中处理复杂状态管理的强大工具。通过正确使用它,可以提高可读性和可维护性,编写灵活高效的代码。

本篇文章是为了帮助初学者大学生理解React Next而准备的输出资料。欢迎留下错误、意见等评论!

bannerAds