zustand

比reduex更轻量级的状态储存工具(类似pinia)

基本使用

使用creat创建

set来修改数据

state来获取数据

返回一个对象

javascript 复制代码
import { create } from "zustand";
const URL = 'http://geek.itheima.net/v1_0/channels'
// 你的存储是一个钩子!你可以将任何东西放入其中:原始、对象、函数。set 函数合并状态。
const useStore = create((set) => ({
    bears: 0,
    // set是用来修改数据的方法
    // 使用state来调用数据修改
    increasePopulation: () => set((state) => ({ bears: state.bears + 1 })), // 基于老数据来计算
    removeAllBears: () => set({ bears: 0 }), // 不用老数据,直接赋值
    updateBears: (newBears) => set({ bears: newBears }), // 需要参数
    //  异步数据直接调请求修改就行
    channellist: [],
    fetchGetList: async () => {
      const res = await fetch(URL)
      const jsonRes = await res.json()
      console.log(jsonRes)
      set({
        channellist: jsonRes.data.channels
      })
    }
    
}))

export default useStore
javascript 复制代码
import useStore from "@/store2"
import { useEffect } from "react";
function App() {
  // const store = useStore();
  const { bears, increasePopulation, fetchGetList, channellist } = useStore();
  // fetchGetList()
  useEffect(() => {
    fetchGetList()
  }, [fetchGetList])
  return (
    <div>
      <h1>{bears}</h1>
      <ul>
        {
          channellist.map(item => <li key={item.id}>{item.name}</li>)
        }
      </ul>
      <button onClick={() => increasePopulation()}>111</button>
    </div>
  )
}

export default App;

切片模式

分模块导入便于管理

javascript 复制代码
// channelsStore
const URL = 'http://geek.itheima.net/v1_0/channels'
export const channelsStore = (set) => ({
    //  异步数据直接调请求修改就行
    channellist: [],
    fetchGetList: async () => {
        const res = await fetch(URL)
        const jsonRes = await res.json()
        console.log(jsonRes)
        set({
            channellist: jsonRes.data.channels
        })
    }
});
javascript 复制代码
// bearsStore
export const bearsStore = (set) => ({
    bears: 0,
    // set是用来修改数据的方法
    // 使用state来调用数据修改
    increasePopulation: () => set((state) => ({ bears: state.bears + 1 })), // 基于老数据来计算
    removeAllBears: () => set({ bears: 0 }), // 不用老数据,直接赋值
    updateBears: (newBears) => set({ bears: newBears }), // 需要参数
})
javascript 复制代码
import { create } from "zustand";
import {channelsStore} from "./modules/channelsStore"
import {bearsStore} from "./modules/bearsStore"

// 你的存储是一个钩子!你可以将任何东西放入其中:原始、对象、函数。set 函数合并状态。
// ...arguments 是一个数组,包含所有传递给 create 的参数。
const useStore = create((...a) => ({
    ...channelsStore(...a),
    ...bearsStore(...a)
}))

export default useStore
相关推荐
linux_cfan1 小时前
17 · 引擎适配器全景:HLS/DASH/Vimeo/Mux/Cast
前端·javascript·音视频
计算机魔术师2 小时前
烧掉2780亿美元还不够?OpenAI的资本豪赌让人头皮发麻
前端
IT_陈寒3 小时前
Java线程池用错参数,我的服务居然悄悄崩溃了
前端·人工智能·后端
卡布鲁3 小时前
React useMemo 与 useCallback 完全指南:原理、场景与避坑
前端·react.js
子非鱼a3 小时前
【XSS】乌托邦·王的实验室
html·xss
碳基修炼3 小时前
排查记:本地 devServer 是 http,浏览器却把 302 重定向升级成了 https
前端·http
步行cgn3 小时前
Spring p 命名空间注入详解
java·前端·spring
何何____3 小时前
Vue 生命周期详解
前端·javascript
江米小枣tonylua4 小时前
TypeScript 全面の拥抱 !Prisma 8 + Electron 升级实战
前端
闪耀之光M784 小时前
npm命令解析
前端