React状态管理——zustand

发布于:2025-06-15 ⋅ 阅读:(15) ⋅ 点赞:(0)

安装

npm i zustand

基本使用

import React from "react";
import { create } from "zustand";
​
// 1. 创建store
const useStore = create((set) => {
  return {
    // 状态数据
    count: 0,
    inc: (data) => {
      set((state) => ({ count: state.count + data }));
    },
  };
});
​
// 2. 绑定store到组件
​
export default function App() {
  const { count, inc } = useStore();
  return (
    <div>
      <div>count:{count}</div>
      <button onClick={() => inc(1)}>点我+1</button>
    </div>
  );
}

异步支持

import React from "react";
import { create } from "zustand";
​
const URL = "http://geek.itheima.net/v1_0/channels";
// 1. 创建store
const useStore = create((set) => {
  return {
    // 状态数据
    count: 0,
    inc: (data) => {
      set((state) => ({ count: state.count + data }));
    },
    // 异步支持
    // 状态数据
    channelList: [],
    fetchGetList: async () => {
      const res = await fetch(URL);
      const jsonRes = await res.json();
      set(() => ({ channelList: jsonRes.data.channels }));
    },
  };
});
​
// 2. 绑定store到组件
​
export default function App() {
  const { count, inc, fetchGetList, channelList } = useStore();
  return (
    <div>
      <div>count:{count}</div>
      <button onClick={() => inc(1)}>点我+1</button>
      <button onClick={() => fetchGetList()}>异步支持</button>
      {channelList.map((item) => (
        <div>{item.id}</div>
      ))}
    </div>
  );
}

​切片模式

import { create } from "zustand";
​
const URL = "http://geek.itheima.net/v1_0/channels";
// 1. 创建counter相关切片
const counterStore = (set) => {
  return {
    // 状态数据
    count: 0,
    inc: (data) => {
      set((state) => ({ count: state.count + data }));
    },
    asyncInc: (data) => {
      setTimeout(() => {
        set((state) => ({ count: state.count + data }));
      }, 2000);
    },
  };
};
// 2. 创建channel相关切片
const channelStore = (set) => {
  return {
    channelList: [],
    fetchGetList: async () => {
      const res = await fetch(URL);
      const jsonRes = await res.json();
      set(() => ({ channelList: jsonRes.data.channels }));
    },
  };
};
// 3.组合切片
const useStore = create((...a) => {
  return {
    ...counterStore(...a),
    ...channelStore(...a),
  };
});
​
export default function App() {
  const { count, inc, fetchGetList, asyncInc, channelList } = useStore();
  return (
    <div>
      <div>count:{count}</div>
      <button onClick={() => inc(1)}>点我+1</button>
      <button onClick={() => asyncInc(2)}>异步+2</button>
      <button onClick={() => fetchGetList()}>异步支持</button>
      {channelList.map((item) => (
        <div key={item.id}>{item.id}</div>
      ))}
    </div>
  );
}

网站公告

今日签到

点亮在社区的每一天
去签到