Skip to content

State Hook

字数
347 字
阅读时间
2 分钟

useState

最基础的 Hook,用于组件内声明状态变量。

基础语法

ts
const [state, setState] = useState(initialState)
  • setState 可接收:
    • 新值: setState(newValue)
    • 更新函数: setState(prev => newValue)

useReducer

用于处理复杂状态逻辑的 Hook。

基础语法

ts
const [state, dispatch] = useReducer(reducer, initialState)
  • reducer 函数接收 (state, action) 返回新状态
  • 通过 dispatch(action) 触发状态更新

使用示例

ts
// 定义 reducer 函数
function todoReducer(state, action) {
  switch (action.type) {
    case 'ADD_TODO':
      return [...state, {
        id: action.id,
        text: action.text,
        completed: false
      }]
    case 'TOGGLE_TODO':
      return state.map(todo =>
        todo.id === action.id
          ? { ...todo, completed: !todo.completed }
          : todo
      )
    default:
      return state
  }
}

// 在组件中使用
function TodoList() {
  const [todos, dispatch] = useReducer(todoReducer, [])

  const addTodo = (text) => {
    dispatch({
      type: 'ADD_TODO',
      id: Date.now(),
      text
    })
  }

  const toggleTodo = (id) => {
    dispatch({
      type: 'TOGGLE_TODO',
      id
    })
  }
}

适用场景

  • 状态逻辑复杂
  • 状态之间有依赖关系
  • 需要集中管理状态更新逻辑

reducer 的本质

reducer 是一个自定义的状态管理器,让开发者完全控制状态的变化逻辑。

与 useState 对比:

  • useState:直接设置新状态
  • useReducer:通过预定义的 reducer 函数计算新状态

优势:

  • 状态更新逻辑更集中,易于维护
  • 可以处理复杂的状态依赖关系
  • 便于测试(reducer 是纯函数)
  • 方便状态逻辑的复用

贡献者

页面历史