Zustand:让React状态管理更简单、更高效

Zustand

这个单词在德语里是状态的意思(发音:促stand)

1. 下载zustand

npm i zustand     

或者

yarn add zustand

2.创建一个store

import { create } from 'zustand'

const useBearStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 }),
}))

Zustand:让React状态管理更简单、更高效_第1张图片

因为zustand会帮你自动合并第一层state,我们这里的bears就是第一层的state;所以我们不需要这里的…;如果你有更深层的状态,第二层第三层的状态,还是需要…的。

因为我项目使用的ts,故而需要加类型:
Zustand:让React状态管理更简单、更高效_第2张图片

import { create } from 'zustand'

type stateType ={
  bears:number;
  increasePopulation:()=>void;
  removeAllBears:()=>void;
}

export const useBearStore = create<stateType>()((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 }),
}))

3.使用方法

这里的useBearStore其实就是一个hook,so可以很方便的被调用;不需要像redux或者useConext那样外面包一层传送门。
然后在componets里面建立一个文件BearBox。

import { Button } from 'antd';

export const BearBox = () => {
  return (
    <div>
      <h1>BearBox</h1>
      <div>
        <Button>add bear</Button>
        <Button>remove bear</Button>
      </div>
    </div>
  );
};

怎么使用useBearStore?:
zustand特别的就是你可以直接从components访问store里的state,不需要在components外面包裹任何context provider;
直接使用useBearStore这个hook;里面参数是一个callback,这个callback给了一个state,这个state就是store里所有的state,然后你可以用它返回你所需要的所有新的state。
Zustand:让React状态管理更简单、更高效_第3张图片

你可能感兴趣的:(知识点小记,react.js,前端,前端框架,zustand)