湖南平台网站建设推荐,网站设计外包合同,如何制作公司内部网页,自媒体横行还有做网站zustand可以说是redux的平替 官网地址#xff1a;https://zustand-demo.pmnd.rs/
1.安装
npm i zustand2.基础使用 // zustand
import { create } from zustand// 1. 创建store
// 语法容易出错
// 1. 函数参数必须返回一个对象 对象内部编写状态数据和方法
// 2. set是用来…zustand可以说是redux的平替 官网地址https://zustand-demo.pmnd.rs/
1.安装
npm i zustand2.基础使用 // zustand
import { create } from zustand// 1. 创建store
// 语法容易出错
// 1. 函数参数必须返回一个对象 对象内部编写状态数据和方法
// 2. set是用来修改数据的专门方法必须调用它来修改数据
// 语法1参数是函数 需要用到老数据的场景
// 语法2参数直接是一个对象 set({ count: 100 })const useStore create((set) {return {// 状态数据count: 0,// 修改状态数据的方法inc: () {set((state) ({ count: state.count 1 }))}}
})// 2. 绑定store到组件
// useStore { count, inc }function App () {const { count, inc } useStore()return (button onClick{inc}{count}/button/)
}export default App3.zustand——异步支持
对于异步的支持不需要特殊的操作直接在函数中编写异步逻辑最后只需要调用set方法传入新状态即可
// zustand
import { useEffect } from react
import { create } from zustand
const URL http://geek.itheima.net/v1_0/channels
// 1. 创建store
// 语法容易出错
// 1. 函数参数必须返回一个对象 对象内部编写状态数据和方法
// 2. set是用来修改数据的专门方法必须调用它来修改数据
// 语法1参数是函数 需要用到老数据的场景
// 语法2参数直接是一个对象 set({ count: 100 })
const useStore create((set) {return {// 状态数据count: 0,// 修改状态数据的方法inc: () {set((state) ({ count: state.count 1 }))},channelList: [],fetchGetList: async () {const res await fetch(URL)const jsonRes await res.json()console.log(jsonRes)set({channelList: jsonRes.data.channels})}}
})// 2. 绑定store到组件
// useStore { count, inc }
function App () {const { count, inc, fetchGetList, channelList } useStore()useEffect(() {fetchGetList()}, [fetchGetList])return (button onClick{inc}{count}/buttonul{channelList.map(item li key{item.id}{item.name}/li)}/ul/)
}export default App4.zustand——切片模式
场景当单个store比较大的时候可以采用切片模式进行模块拆分组合类似于模块化
// zustand
import { useEffect } from react
import { create } from zustand
const URL http://geek.itheima.net/v1_0/channels// store
// counterStore
// channelStore
// index.js// 1. 拆分子模块 再组合起来const createCounterStore (set) {return {// 状态数据count: 0,// 修改状态数据的方法inc: () {set((state) ({ count: state.count 1 }))},}
}const createChannelStore (set) {return {channelList: [],fetchGetList: async () {const res await fetch(URL)const jsonRes await res.json()console.log(jsonRes)set({channelList: jsonRes.data.channels})}}
}const useStore create((...a) {return {...createCounterStore(...a),...createChannelStore(...a)}
})function App () {// 2. 组件使用const { count, inc, fetchGetList, channelList } useStore()useEffect(() {fetchGetList()}, [fetchGetList])return (button onClick{inc}{count}/buttonul{channelList.map(item li key{item.id}{item.name}/li)}/ul/)
}export default App