广东商城网站建设多少钱,网页在线设计,wordpress前端插件,贸易公司网站建设方案如果有兴趣了解更多用法及 api #xff0c;点击此处解锁中文文档
前言
是不是觉得 Redux 很难用#xff1f;想用 Context 代替#xff0c;但是你知道吗#xff0c;Context 也有个很大的缺点#xff1a;
context value发生变化时#xff0c;所有用到这个context的组件都…如果有兴趣了解更多用法及 api 点击此处解锁中文文档
前言
是不是觉得 Redux 很难用想用 Context 代替但是你知道吗Context 也有个很大的缺点
context value发生变化时所有用到这个context的组件都会被重新渲染即使 component 需要的 state 可能根本沒有变动。基于 context 维护的模块越多影响范围越大, 某些情况下会导致页面明显卡顿。另外它依赖 Context Provider 包裹你的应用程序。
那么试试 zustand 吧当然你可以选择 mobx zustand 与 mobx 最大的差别在于
zustand 的状态更新遵循 react 思想采用自然不可变更新, 而 mobx 类似 vue基于数据劫持直接修改状态本身。体现在开发层面最直观的差异就是 zustand 状态更新新状态覆盖旧状态 state {a: 1}update(){stae {a: 2}
}mobx 状态更新直接修改属性值 state {a: 1}update(){stae.a
}React 三部曲
Step 1: 安装
npm install zustand # or yarn add zustandStep 2: Store 初始化
创建的 store 是一个 hook你可以放任何东西到里面基础变量对象、函数状态必须不可改变地更新set 函数合并状态以实现状态更新。
import { create } from zustandconst useBearStore create((set) ({bears: 0,increasePopulation: () set((state) ({ bears: state.bears 1 })),removeAllBears: () set({ bears: 0 }),
}))Step 3: Store 绑定组件就完成了!
可以在任何地方使用钩子不需要提供 provider。 基于 selector 获取您的目标状态组件将在状态更改时重新渲染。
选择目标状态bears
function BearCounter() {const bears useBearStore((state) state.bears)return h1{bears} around here .../h1
}更新目标状态bears
function Controls() {const increasePopulation useBearStore((state) state.increasePopulation)return button onClick{increasePopulation}one up/button
}Vue 三部曲
什么你还想试试在 Vue 中使用那么 Step1 与 Step2 基本一致不同的是 Step3 (Store 绑定组件)
Step 1: 安装
npm install zustand-vue # or yarn add zustand-vueStep 2: Store 初始化
创建的 store 是一个 hook你可以放任何东西到里面基础变量对象、函数状态必须不可改变地更新set 函数合并状态以实现状态更新。
import create from zustand-vue;const useBearStore create((set) ({bears: 0,increasePopulation: () set((state) ({ bears: state.bears 1 })),removeAllBears: () set({ bears: 0 }),
}))export default useBearStoreStep 3: Store 绑定组件就完成了!
基于 selector 获取您的目标状态组件将在状态更改时重新渲染。 Store 绑定组件在 vue3 与 vue2 中有所不同。 templatedivstore.bears: {{ bears }}/divbutton clickincreasePopulationincreasePopulation/buttonbutton clickremoveAllBearsremoveAllBears/button
/templatescript
import useBearStore from ./store;const increasePopulation useBearStore((state) state.increasePopulation);
const removeAllBears useBearStore((state) state.removeAllBears);export default {data() {return {store: useBearStore(),bears: useBearStore((state) state.bears),};},methods: {increasePopulation,removeAllBears,},
};