一款redux替代品的状态管理
实现:
- react状态管理
- ts支持
- 数据持久化储存
- store模块封装
- 三种引入使用的方法
1、install
npm install zustand # or yarn add zustand
2、useCountStore.tsx
import { create } from 'zustand'; import { persist, createJSONStorage, devtools } from 'zustand/middleware'; interface CountState { count: number; increment: () => void; decrement: () => void; name: string; setName: (x:string) => void; resetName: () => void; } const useCountStore = create<CountState>()( devtools( persist( set => ({ // count count: 0, increment: () => set(state => { return { count: state.count + 1 } }), decrement: () => set(state => ({ count: state.count - 1 })), // name name: '--', setName: (name:string) => set(() => ({ name })), resetName: () => set(() => ({ name: '--' })) }), { name: 'zustand-storage', storage: createJSONStorage(() => sessionStorage), } ) ) ) export default useCountStore
3、index.tsx
import React from 'react'; import useCountStore from './useCountStore'; import { shallow } from 'zustand/shallow'; const ZustandView = () => { // way 1 // const count = useCountStore((state:any) => state.count) // const increaseCount = useCountStore((state:any) => state.increment) // const decreaseCount = useCountStore((state:any) => state.decrement) // const name = useCountStore((state:any) => state.name) // const setName = useCountStore((state:any) => state.setName) // const resetName = useCountStore((state:any) => state.resetName) // way 2 // const { count, increment, decrement, name, setName, resetName } = useCountStore((state:any) => ({ // count: state.count, // increment: state.increment, // decrement: state.decrement, // name: state.name, // setName: state.setName, // resetName: state.resetName, // }), shallow) // way 3 const [ count, increment, decrement, name, setName, resetName] = useCountStore((statte:any) => [ statte.count, statte.increment, statte.decrement, statte.name, statte.setName, statte.resetName, ], shallow) return ( <div> <h1>{count}</h1> <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> <br /> <h2>{name}</h2> <button onClick={() => setName('qwe')}>Set Name</button> <button onClick={resetName}>Reset Name</button> <br /> <button onClick={() => console.log(count)}>look</button> </div> ); }; export default ZustandView;
4、使用
import ZustandPage from './pages/zustandPage'; export default function App() { return <> <ZustandPage></ZustandPage> </> };
官网:https://github.com/pmndrs/zustand
标签:count,zustand,const,name,setName,useCountStore,ts,react,state From: https://www.cnblogs.com/-roc/p/17170648.html