React 学习——zustand切片拆分
模块比较大的时候,功能相对独立的时候,可以单独抽离出来;
对在组件中应用没有任何影响。
import { useEffect } from 'react'
import { create } from 'zustand'
// counter store
const createCounterStore = (set=>{
return {
count: 0,
add:()=>{ set(state => ({ count: state.count + 1 })) },
sub:()=>{ set(state => ({count: state.count - 1})) },
}
})
// channel store
const createChannelStore = (set=>{
return {
channelList: [],
fetchChannelList: async()=>{
const res = await fetch('http://geek.itheima.net/v1_0/channels')
const jsonData = await res.json()
set(state => ({ channelList: jsonData.data.channels }))
}
}
})
// 组合
const useStore = create((...a)=>{
return {
...createCounterStore(...a),
...createChannelStore(...a)
}
})
const App = () => {
const { count,add,sub,channelList,fetchChannelList } = useStore();
useEffect(()=>{
fetchChannelList()
},[])
return (
<div className="home">
<button onClick={add}>+</button>
<span>{count}</span>
<button onClick={sub}>-</button>
<ul>
{channelList.map(item=>(<li key={item.id}>{item.name}</li>))}
</ul>
</div>
)
}
export default App