比reduex更轻量级的状态储存工具(类似pinia)
基本使用
使用creat创建
set来修改数据
state来获取数据
返回一个对象
javascript
import { create } from "zustand";
const URL = 'http://geek.itheima.net/v1_0/channels'
// 你的存储是一个钩子!你可以将任何东西放入其中:原始、对象、函数。set 函数合并状态。
const useStore = create((set) => ({
bears: 0,
// set是用来修改数据的方法
// 使用state来调用数据修改
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })), // 基于老数据来计算
removeAllBears: () => set({ bears: 0 }), // 不用老数据,直接赋值
updateBears: (newBears) => set({ bears: newBears }), // 需要参数
// 异步数据直接调请求修改就行
channellist: [],
fetchGetList: async () => {
const res = await fetch(URL)
const jsonRes = await res.json()
console.log(jsonRes)
set({
channellist: jsonRes.data.channels
})
}
}))
export default useStore
javascript
import useStore from "@/store2"
import { useEffect } from "react";
function App() {
// const store = useStore();
const { bears, increasePopulation, fetchGetList, channellist } = useStore();
// fetchGetList()
useEffect(() => {
fetchGetList()
}, [fetchGetList])
return (
<div>
<h1>{bears}</h1>
<ul>
{
channellist.map(item => <li key={item.id}>{item.name}</li>)
}
</ul>
<button onClick={() => increasePopulation()}>111</button>
</div>
)
}
export default App;
切片模式
分模块导入便于管理
javascript
// channelsStore
const URL = 'http://geek.itheima.net/v1_0/channels'
export const channelsStore = (set) => ({
// 异步数据直接调请求修改就行
channellist: [],
fetchGetList: async () => {
const res = await fetch(URL)
const jsonRes = await res.json()
console.log(jsonRes)
set({
channellist: jsonRes.data.channels
})
}
});
javascript
// bearsStore
export const bearsStore = (set) => ({
bears: 0,
// set是用来修改数据的方法
// 使用state来调用数据修改
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })), // 基于老数据来计算
removeAllBears: () => set({ bears: 0 }), // 不用老数据,直接赋值
updateBears: (newBears) => set({ bears: newBears }), // 需要参数
})
javascript
import { create } from "zustand";
import {channelsStore} from "./modules/channelsStore"
import {bearsStore} from "./modules/bearsStore"
// 你的存储是一个钩子!你可以将任何东西放入其中:原始、对象、函数。set 函数合并状态。
// ...arguments 是一个数组,包含所有传递给 create 的参数。
const useStore = create((...a) => ({
...channelsStore(...a),
...bearsStore(...a)
}))
export default useStore