zustand
简单使用
import { create } from "zustand";
const useCount = create((set) => ({
count: 0,
plus: () => set((state) => ({count: state.count + 1})),
minus: () => set((state) => ({count: state.count - 1})),
reset: () => set({count: 0}),
}));function Counter() {
const count = useCount((state) => state.count);
return <h1>{count}</h1>;
}
function Controls() {
const plus = useCount((state) => state.plus);
const minus = useCount((state) => state.minus);
const reset = useCount((state) => state.reset);
return (
<>
<button onClick={plus}>+</button>
<button onClick={minus}>-</button>
<button onClick={reset}>重置</button>
</>
);
}state 更新渲染组件
单个 state 更新渲染
多个 state 更新渲染
自定义函数控制渲染
覆盖 state
异步操作
从 action 中读取 state
记忆处理器
useCallback
不依赖于作用域的处理器
在 React 组件之外读写 state
自定义 hooks 读写 state
使用订阅处理器(中间件)
订阅处理器(中间件)使用 TS
瞬时更新 ref(用于频繁发生的状态变化)
更新嵌套的状态,使用
Immer
中间件
按自己喜欢的方式管理 store
管理中间件
在管理中间件中使用 TS
状态持久化中间件 persist
像 Redux 一样编写代码
在 React 事件处理程序之外调用 actions
使用 Redux 开发工具
React context
3. createContext 使用 props 初始化(在 TS 中)
TypeScript 类型定义
1. 类型定义
2.使用combine 并让 tsc 推断类型
combine 并让 tsc 推断类型最后更新于
