跟写普通方法一样,只不过再最后赋值的时候用set就行了。
javascript
import { useEffect } from 'react'
import { create } from 'zustand'
// 创建store
const useStore = create(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 App = () => {
const { channelList,fetchChannelList } = useStore();
useEffect(()=>{
fetchChannelList()
},[])
return (
<div className="home">
<ul>
{channelList.map(item=>(<li key={item.id}>{item.name}</li>))}
</ul>
</div>
)
}
export default App