欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

React 状态管理工具快速入门!

最编程 2024-10-18 15:40:36
...

创建store(状态数据,操作方法) = = =(绑定组件)= = =》 component(消费数据和方法)

  1. 安装:npm i zustand
  2. 创建store
  3. 绑定store到组件
import {create} from 'zustand'
// 1. 创建store
const useStore = create((set) => {
    return {
        // 状态数据
        count: 0,
        // 修改状态数据的方法
        inc: () => {
            // set是用来修改数据的专门方法,必须调用它来修改数据
            // 语法1:参数是函数,需要用到老数据的的场景
            set((state) => ({count: state.count + 1}))
            // 语法2:参数直接是一个对象
            // set({count: 100})
        }
    }
})

function App() {
    // 2.绑定store到组件
    const {count, inc} = useStore()
    return (
        <div>
            <button onClick={inc}>{count}</button>
        </div>
    );
}

export default App;