技术文献

React Hooks: useReducer

2026-10-02

useReducer的函数,最主要有两个东西:➀数据状态  ➁操作状态的方法。


㈠ 从useReducer()中结构出数据状态和操作状态的方法:

const [state,dispatch ] = useReducer()

㈡ useReducer()函数接收两个参数:

⑴操作数据的方法的入口函数:reducer

⑵数据状态:state

const [state,dispatch ] = useReducer(reducer, {
       count: 0,
       error: null,
   });

㈢ 定义操作方法的入口函数 reducer

interface State {
   count: number;
   error: string | null;
}

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

function reducer(state: State, action: Action) {
   const type = action.type;
   switch (type) {
       case 'increment':{
           const newCount=state.count + 1;
           const hasError = newCount > 12;
           return {
               ...state,
               count: hasError?state.count:state.count + 1,
               error: hasError?'not over 12':null,
           };}
       case 'decrement':{
           const newCount=state.count - 1;
           const hasError = newCount < 1;
           return {
               ...state,
               count: hasError?state.count:state.count-1,
               error: hasError?'not less 1':null,
           };}
       default: {
           return state;
       }
   }
}

㈣ 调用数据状态和方法:

 <div>count:{state.count}</div>
 <button onClick={()=>{dispatch({type:'increment'})}}>+1</button>

全部源代码:↓

import {useReducer} from "react";
type Props = {
};
interface State {
   count: number;
   error: string | null;
}
interface Action {
   type:'increment' | 'decrement';
}
function reducer(state: State, action: Action) {
   const type = action.type;
   switch (type) {
       case 'increment':{
           const newCount=state.count + 1;
           const hasError = newCount > 12;
           return {
               ...state,
               count: hasError?state.count:state.count + 1,
               error: hasError?'not over 12':null,
           };}
       case 'decrement':{
           const newCount=state.count - 1;
           const hasError = newCount < 1;
           return {
               ...state,
               count: hasError?state.count:state.count-1,
               error: hasError?'not less 1':null,
           };}
       default: {
           return state;
       }
   }
}
export function Child3({}: Props) {
   const [state,dispatch ] = useReducer(reducer, {
       count: 0,
       error: null,
   });
   return (
       <div>
           <div>count:{state.count}</div>
           <div>
               <button onClick={()=>{dispatch({type:'increment'})}}>+1</button>
               <button onClick={()=>{dispatch({type:'decrement'})}}>-1</button>
           </div>
           <div>{state.error&&<span>error:{state.error}</span>}</div>
       </div>
   );
}