Zustand

7/17/2020 react

# 1.Zustand


很简单的状态管理,基于函数式和hooks

安装

// 创建项目
yarn create vite react-zustand --template react
// 安装redux配套工具
yarn add  zustand
// 启动项目
yarn dev
1
2
3
4
5
6

新建store目录结构

src

  • store
    • counterStore.js
  • App.js

src/store/counterStore.js

import create from 'zustand'

// 模拟异步请求
const listApi = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(['react', 'vue', 'angular'])
    }, 2000)
  })
}

const useCounterStore = create((set) => ({
  // 初始化数据
  count: 0,
  list: [],
  // 修改数据的方法
  increase: () => set(state => ({
    count: state.count + 1
  })),
  decrease: () => set(state => ({
    count: state.count - 1
  })),
  addList: async () => {
    const res = await listApi()
    set({
      list: res
    })
  }
}))
export default useCounterStore
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

组件中使用store

import { useEffect, useRef } from 'react'
import useCounterStore from './store/counterStore'
function App () {
  const count = useCounterStore((state) => state.count)
  const list = useCounterStore((state) => state.list)
  const handelIncrease = useCounterStore(state => state.increase)
  const handelDecrease = useCounterStore(state => state.decrease)
  const addList = useCounterStore(state => state.addList)
  const renderRef = useRef(true)
  useEffect(() => {
    if (renderRef.current) {
      renderRef.current = false
      return
    }
    addList()
  }, [])
  return (
    <div className="App">
      <h1>{count}</h1>
      <button onClick={handelIncrease}>增加</button>
      <button onClick={handelDecrease}>减小</button>
      <hr />
      <ul>
        {
          list.map(item => <li key={item}>{item}</li>)
        }
      </ul>
    </div>
  )
}
export default App
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
更新: 8/22/2022, 2:37:27 PM