zustand-极简的状态管理工具

2 阅读1分钟

快速上手

Zustand Documentation

npm i zustand

store/index.js - 创建store

import { create } from 'zustand'
// 创建store
// 1. 函数参数必须返回一个对象 对象内部编写状态数据和方法
// 2. set是用来修改数据的专门方法必须调用它来修改数据
// 语法1:参数是函数需要用到老数据的场景
// 语法2:参数直接是一个对象 set({count:100})
const useStore = create((set) => {
  return {
    count: 0,
    inc: () => {
      set(state => ({ count: state.count + 1 }))
      // set((state) => { return { count: state.count + 1 }})
    }
  }
})
​
export default useStore

app.js - 绑定组件

import useStore from './store/useCounterStore.js'// 绑定store到组件
// useStore => { count,inc }
function App() {
  const { count, inc } = useStore()
  return <button onClick={inc}>{count}</button>
}
​
export default App

异步支持

对于异步操作的支持不需要特殊的操作,直接在函数中编写异步逻辑,最后把接口的数据放到set函数中返回即可

store/index.js - 创建store

import { create } from 'zustand'const URL = 'http://geek.itheima.net/v1_0/channels'const useStore = create((set) => {
  return {
    count: 0,
    ins: () => {
      return set(state => ({ count: state.count + 1 }))
    },
    channelList: [],
    fetchChannelList: async () => {
      const res = await fetch(URL)
      const jsonData = await res.json()
      set({channelList: jsonData.data.channels})
    }
  }
})
​
export default useStore

app.js - 绑定组件

import { useEffect } from 'react'
import useChannelStore from './store/channelStore'function App() {
  const { channelList, fetchChannelList } = useChannelStore()
 
  useEffect(() => {
    fetchChannelList()
  }, [fetchChannelList]) // 如果是传空数组useEffect只会执行一次
​
  return (
    <ul>
      {channelList.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  )
}
​
export default App

切片模式

场景:当我们单个store比较大的时候,可以采用一种切片模式进行模块拆分再组合

拆分并组合切片

import { create } from 'zustand'// 创建counter相关切片
const createCounterStore = (set) => {
  return {
    count: 0,
    setCount: () => {
      set(state => ({ count: state.count + 1 }))
    }
  }
}
​
// 创建channel相关切片
const createChannelStore = (set) => {
  return {
    channelList: [],
    fetchGetList: async () => {
      const res = await fetch(URL)
      const jsonData = await res.json()
      set({ channelList: jsonData.data.channels })
    }
  }
}
​
// 组合切片
const useStore = create((...a) => ({
  ...createCounterStore(...a),
  ...createChannelStore(...a)
}))

组件使用

function App() {
  const {count, inc, channelList, fetchChannelList } = useStore()
  return (
    <>
      <button onClick={inc}>{count}</button>
      <ul>
        {channelList.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </>
  )
}
​
export default App