发布于 2026-01-06 5 阅读
0

Usando Zustand 与 React JS! 🚀

Usando Zustand 与 React JS! 🚀

React JS 的现代应用中的管理和算法是必需的。我敢于介绍一种“ Zustand ”,它是一种流行的管理方式和应用程序。

Cualquier Tipo de Feedback es bienvenido, gracias y espero disfrutes el articulo.🤗

🚨 注意:需要使用React 和 TypeScript的基础

 

内容表

📌 ¿Qué es Zustand?

📌使用 Zustand 的优点。

📌 Creando el proyecto。

📌 Creando 一家商店。

📌前往商店。

📌继续多个国家。

📌 ¿Por qué usamos la función 浅?

📌 Actualizando el estado.

📌 Creando una acción。

📌进入商店。

📌执行操作。

📌结论。

 

🚀 ¿Qué es Zustand?

它是小规模、快速且可升级的管理解决方案。国家的管理是集中化和行动的基础。
Zustand 是由 Jotai 和 React-spring 的创建者开发的,
Zustand 是使用 React 和 Angular、Vue JS 或 JavaScript 原生技术。
Zustand 是 Redux、Jotai Recoil 等其他版本的替代方案。

⭕ Ventajas de usar Zustand.

  • Menos código repetido(与 Redux 比较)。
  • 方便的文档。
  • 灵活性
    • 使用简单的格式,使用 TypeScript,将其整合为不可更改的,或包含编写代码和支持者 Redux(减速器和调度)。
  • 无需将应用程序与 Redux 进行验证。
  • 我们将单独渲染组件。

🚀 Creando el proyecto.

Al proyecto le colocaremos el nombre de:(zustand-tutorial可选,tu le puedes poner el nombre que gustes)。

npm init vite@latest
Enter fullscreen mode Exit fullscreen mode

与 Vite JS 结合的奶油和与 TypeScript 结合的 React 选择。

执行命令时,请执行以下操作:

cd zustand-tutorial
Enter fullscreen mode Exit fullscreen mode

Luego instalamos las dependentencias。

npm install
Enter fullscreen mode Exit fullscreen mode

使用代码编辑器(en mi caso VS code)编写项目。

code .
Enter fullscreen mode Exit fullscreen mode

🚀 创建一家商店。

Primero debemos 安装 Zustand:

npm install zustand
Enter fullscreen mode Exit fullscreen mode

安装图书馆、创建地毯src/store和地毯商店是新档案馆bookStore.ts和东部档案馆的必需品,创建新商店。

Primero importamos el paquete de zustand y lo nombramos create

import create from 'zustand';
Enter fullscreen mode Exit fullscreen mode

Luego Creamos una Constante con el nombre useBookStore(esto es porque zustand usa hooks por debajo y en su documentación nombre lasstores de esta manera)。

商店用途定义为创建功能。

import create from 'zustand';

export const useBookStore = create();
Enter fullscreen mode Exit fullscreen mode

创建一个回调函数,然后返回一个对象,创建一个商店。

import create from 'zustand';

export const useBookStore = create( () => ({

}));
Enter fullscreen mode Exit fullscreen mode

最好的汽车完成,我们可以定义新商店的属性,就像功能一样。

Luego establecemos el valor inicial de las propiedades,en este caso la propiedad amount inicialmente sera 40。

import create from 'zustand';

interface IBook {
    amount: number 
}

export const useBookStore = create<IBook>( () => ({
    amount: 40 
}));
Enter fullscreen mode Exit fullscreen mode

🚀 Accediendo a la store.

进入我们的商店,需要重要的迪查商店。
我们的档案src/App.tsx很重要,我们的商店。

Sin necesidad de usarprovedores como en Redux, podemos usar nuestra store casi en cualquier lugar ("casi" ya que sigue las reglas de los hooks, ya que la store básicamente es un hook por debajo)。

美洲驼是一个新的钩子,可以作为其他钩子,单独为中间的参数提供回调,以获取存储和自动完成的功能。

import { useBookStore } from './store/bookStore';
const App = () => {

  const amount = useBookStore(state => state.amount)

  return (
    <div>
      <h1>Books: {amount} </h1>
    </div>
  )
}
export default App
Enter fullscreen mode Exit fullscreen mode

⭕ 接受多个国家。

Supongamos que tienes mas de un estado en tu store, por ejemplo, agregamos el titulo:

import create from 'zustand';

interface IBook {
    amount: number
    author: string
}

export const useBookStore = create<IBook>( () => ({
    amount: 40,
    title: "Alice's Adventures in Wonderland"
}));
Enter fullscreen mode Exit fullscreen mode

Para acceder a mas estados podríamos hacer lo siguiente:

Caso 1 - Una forma es de manera individual, ir accediendo al estado, creando nuevas Constantes。

import { useBookStore } from './store/bookStore';
const App = () => {

  const amount = useBookStore(state => state.amount)
  const title = useBookStore(state => state.title)

  return (
    <div>
      <h1>Books: {amount} </h1>
    </div>
  )
}
export default App
Enter fullscreen mode Exit fullscreen mode

Caso 2 - 如果您想创建一个具有多个国家或属性的特殊对象。 Y para decirle a Zustand que difunda el object superficialmente, debemos pasar la funciónshallow

import shallow from 'zustand/shallow'
import { useBookStore } from './store/bookStore';

const App = () => {

  const { amount, title } = useBookStore(
    (state) => ({ amount: state.amount, title: state.title }),
    shallow
  )

  return (
    <div>
      <h1>Books: {amount} </h1>
      <h4>Title: {title} </h4>
    </div>
  )
}
export default App
Enter fullscreen mode Exit fullscreen mode

Aunque lo mejor seria también el store colocarlo en un hook Aparte si es que llega a crecer demasiado encuestión de propiedades

Tanto en el caso 1 como el caso 2 los componentes se volverán a renderizar cuando el title y amount cambien.

🔴 ¿你的功能很浅吗?

En el caso anterior donde accedemos a varios estados de la store, usamos la función slim , ¿por qué ?

如果没有浅薄的缺陷,Zustand detectora los cambios con igualdad estricta (old === new), lo cual es eficiente para estados atómicos

 const amount = useBookStore(state => state.amount)
Enter fullscreen mode Exit fullscreen mode

Pero en el caso 2, no estamos obteniendo un estado atómico, sino un objeto (pasa lomismo si usamos un arreglo)。

  const { amount, title } = useBookStore(
    (state) => ({ amount: state.amount, title: state.title }),
    shallow
  )
Enter fullscreen mode Exit fullscreen mode

由于受限制的缺陷,我们将评估对象并重新渲染对象。

如果浅浅的物体/排列与克拉夫斯的比较,那么新的娱乐和新的渲染是不同的。

🚀 Actualizando el estado.

商店的实际状态和修改src/store/bookStore.ts商店的功能将被修改。

通过创建功能的回调,设置各种参数的功能,启动功能,并允许商店实际使用。

export const useBookStore = create<IBook>(( set ) => ({
    amount: 40
}));
Enter fullscreen mode Exit fullscreen mode

⭕ Creando una acción.

Primero Creamos 是一个新的属性,可实现数量更新数量,并可根据参数的数量进行配方。

import create from 'zustand'

interface IBook {
    amount: number
    updateAmount: (newAmount: number) => void
}

export const useBookStore = create<IBook>((set) => ({
    amount: 40,
    updateAmount: (newAmount: number ) => {}
}));
Enter fullscreen mode Exit fullscreen mode

功能更新的数量可以设置目标,庄园参考属性和实际情况。

import create from 'zustand'

interface IBook {
    amount: number
    updateAmount: (newAmount: number) => void
}

export const useBookStore = create<IBook>( (set) => ({
    amount: 40,
    updateAmount: (newAmount: number ) => set({ amount: newAmount }),
}));
Enter fullscreen mode Exit fullscreen mode

该功能设置为参数功能,可用于获取前面的状态。

选择要实现的国家(suponiendo que tengo más propiedades)和单独的实际国家需要,en este caso el amount

:您的主要财产是在肖恩的物品或坎比亚常数的状态下进行的。

updateAmount: (newAmount: number ) => set( state => ({ ...state, amount: state.amount + newAmount }))
Enter fullscreen mode Exit fullscreen mode

请按以下步骤操作!

updateAmount: async(newAmount: number ) => {
    // to do fetching data
    set({ amount: newAmount })
}
Enter fullscreen mode Exit fullscreen mode

💡 注意:函数设置接受第二个参数布尔值,因为错误。在融合的过程中,重新建立国家模型。请勿在商店中购买任何重要部件。

  updateAmount: () => set({}, true), // clears the entire store, actions included,

Enter fullscreen mode Exit fullscreen mode

⭕ 进入商店。

定义国家用途的功能,是否能获得国家的价值?

Bueno para eso tenemos el segundo parámetro a lado del set , que es get() que nos da acceso al estado。

import create from 'zustand'

interface IBook {
    amount: number
    updateAmount: (newAmount: number) => void
}

export const useBookStore = create<IBook>( (set, get) => ({
    amount: 40,
    updateAmount: (newAmount: number ) => {

        const amountState = get().amount

        set({ amount: newAmount + amountState })
        //is the same as:
        // set(state => ({ amount: newAmount + state.amount  }))
    },
}));
Enter fullscreen mode Exit fullscreen mode

⭕ Ejecutando la acción.

执行此操作时,只需简单地获取前面的属性即可。执行此操作时,需要的参数是唯一的。

import { useBookStore } from './store/bookStore';
const App = () => {

  const amount = useBookStore(state => state.amount)
  const updateAmount = useBookStore(state => state.updateAmount)

  return (
    <div>

      <h1> Books: {amount} </h1>

      <button 
        onClick={ () => updateAmount(10) } 
      > Update Amount </button>

    </div>
  )
}
export default App
Enter fullscreen mode Exit fullscreen mode

🚀 结论。

为了方便地访问和实现国家,您可以与其他国家的代理人进行交流。

就我个人而言,Zustand me ha agradado bastante por sus characterísticas antes mencionadas, es una de Mis librías favorites para gestionar el estado, así como Redux Toolkit。 Sin duda deberías de darle una oportunidad para usarla en algún proyecto 😉。

Espero haberte ayudado a entender mejor el como funciona y como usar esta librería,非常感谢 por llegar hasta aquí! 🤗

我们将邀请您来评论有关阿尔古纳的其他重要特征或主要实践。 🙌

文章来源:https://dev.to/franklin030601/usando-zustand-con-react-js-33le