Zustand 是一个轻量级的状态管理库,在 React 应用中非常有用。以下是一个通俗易懂的教程,帮助你快速上手 Zustand。
安装
首先,使用 npm 或 yarn 安装 Zustand:
npm install zustand
或者
yarn add zustand
创建状态
使用 Zustand 创建一个状态非常简单。你需要创建一个 store,并定义状态和操作。
import create from 'zustand';
const useStore = create(set => ({
count: 0,
increment: () => set(state => ({
count: state.count + 1 })),
decrement: () => set(state => ({
count: state.count - 1 }))
}));
在上面的例子中,我们创建了一个 store,包含一个 count 状态和两个操作:increment 和 decrement。
使用状态
在你的 React 组件中,你可以使用这个 store:
import React from 'react';
import {
useStore } from './store';
function Counter() {
const {
count, increment, decrement } = useStore();
return (
<div>
<h1>{
count}</h1>
<button onClick={
increment}>Increment</button>
<button onClick={
decrement}>Decrement</button>
</div>
);
}
export default Counter;
中间件
Zustand 支持中间件,可以用来扩展 store 的功能。例如,你可以使用 redux 中间件来添加 Redux 开发工具支持:
import create from 'zustand';
import {
devtools } from 'zustand/middleware';
const useStore = create(devtools(set => ({
count: 0,
increment: () => set(state => ({
count: state.count + 1 })),
decrement: () => set(state => ({
count: state.count - 1 }))
})));
异步操作
Zustand 也支持异步操作。你可以在操作中使用 async/await:
import create from 'zustand';

最低0.47元/天 解锁文章
724

被折叠的 条评论
为什么被折叠?



