zustand使用

安装

npm install zustand

对于简单的状态

(一层)

定义

E:\next-blog\zustandtest\store\index.ts

import { create } from 'zustand'


interface State {
    count: number,
    todoList: string[]
    todoItem: string
    name: string
}

type Action = {
    increaseCount: () => void
    setTodoList: (item: string) => void
    setTodoItem: (item: string) => void
    updateName: (item: string) => void
}

export const useStore = create<State & Action>()(
    (set) => ({
        count: 0,
        todoList: [],
        todoItem: "",
        name: "",
        increaseCount: () => set((state) => ({ count: state.count + 1 })),
        setTodoList: (item) => set((state) => ({ todoList: [...state.todoList, item] })),
        setTodoItem: (item) => set(() => ({ todoItem: item })),
        updateName: (item) => set(() => ({ name: item }))
    }))
import { create } from 'zustand'

interface State {
    switchPage: string
}

type Action = {
    setswitchPage: (item: string) => void
}

export const useStore = create<State & Action>()(
    (set) => ({
        switchPage: "file",
        setswitchPage: (item) => set(() => ({ switchPage: item }))
    }))

调用

E:\next-blog\zustandtest\components\Todolists.tsx

"use client"
import { useStore } from '@/store'
import React from 'react'

const Todolists = () => {
    const todolist = useStore((state) => state.todoList)
    const todoItem = useStore((state) => state.todoItem)
    const setTodoItem = useStore((state) => state.setTodoItem)
    const setTodoList = useStore((state) => state.setTodoList)

对于复杂的状态

需要用到中间件

npm install immer

(多层)

import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'

interface ILog {
    where: string,
    who: string,
    done: string
}

interface State {
    log: ILog
}

type Action = {
    setLogName: (item: string) => void
    setLogWhere: (item: string) => void
    setLogDone: (item: string) => void
}

export const useStore = create<State & Action>()(
    immer((set) => ({
        log: {
            who: '',
            where: '',
            done: ''
        },
        setLogName: (item) =>
            set((state) => {
                state.log.who = item
            }),
            // 对象状态
        setLogWhere: (item) =>
            set((state) => {
                state.log.where = item
            }),
        setLogDone: (item) =>
            set((state) => {
                state.log.done = item
            }),
    })))
updateName: (item) => set(() => ({ name : item })),
updateName: (item) => set((state) => { state.name = item }),  //immer包裹

偶尔分享web开发知识
某破站
blog

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值