zustand管理工具--React

npm i zustand

1.函数参数必须返回一个对象 对象内部编写状态数据和方法

2.set是用来修改数据的专门方法必须调用它来修改数据

import { useEffect } from "react";
import { create } from "zustand";

// 1. 创建store
const goodsStore = create((set) => ({
  count: 1,
  inc: () => set((state) => ({ count: state.count + 1 })),
  channelList: [],
  // 异步方法
  fetchChannelList: async () => {
    const res = await fetch(URL);
    const jsonData = await res.json();

    set({ channelList: jsonData.data.channels });
  },
}));

// 2. 绑定store到组件
function Counter() {
  const { count, inc, channelList, fetchChannelList } = goodsStore();

  useEffect(() => {
    fetchChannelList()
  }, [fetchChannelList])

  return (
    
    {channelList.map((item) => { return
  • {item.name}
  • ; })}
); } export default Counter;

3.切片模式--模块化

import { useEffect } from "react";
import { create } from "zustand";

// 1. 创建store
const goodsStore = (set) => ({
  count: 1,
  inc: () => set((state) => ({ count: state.count + 1 })),
});

const channelListStore = (set) => ({
  channelList: [],
  // 异步方法
  fetchChannelList: async () => {
    const res = await fetch(URL);
    const jsonData = await res.json();

    set({ channelList: jsonData.data.channels });
  },
});

const useStore = create((...a) => ({
    ...goodsStore(...a),
    ...channelListStore(...a),
  }));

// 2. 绑定store到组件
function Counter() {
  const { count, inc, channelList, fetchChannelList } = useStore();

  useEffect(() => {
    fetchChannelList();
  }, [fetchChannelList]);

  return (
    
    {channelList.map((item) => { return
  • {item}
  • ; })}
); } export default Counter;

你可能感兴趣的:(react.js,javascript,前端)