从服务器状态派生客户端状态
No translations available.- Add translation
暂无翻译。- 添加翻译
Just as I came back from vacation, I saw this reddit question about the biggest trade-off when it comes to using zustand
. The code looked something like this (I altered it slightly for updated syntax and packed it into a custom hook):
我刚度假回来,就看到了这个 reddit 问题,讨论使用 zustand
时最大的权衡。代码大致如下(我稍微调整了语法,并封装成了一个自定义 hook):
Copymanual-sync: copy code to clipboard 1constuseSelectedUser=()=>{ 2const{ data: users }=useQuery({ 6const{ selectedUserId, setSelectedUserId }=useUserStore() 8// If the selected user gets deleted from the server, 9// Zustand won't automatically clear selectedUserId 10// You have to manually handle this: 12if(!users?.some((u)=> u.id=== selectedUserId)){ 13setSelectedUserId(null)// Manual sync required 15},[users, selectedUserId]) 17return[selectedUserId, selectedUserId]
Copymanual-sync: 复制代码到剪贴板 1constuseSelectedUser=()=>{ 2const{ data: users }=useQuery({ 6const{ selectedUserId, setSelectedUserId }=useUserStore() 8// 如果所选用户从服务器端被删除, 9// Zustand 不会自动清除 selectedUserId 10// 你需要手动处理: 12if(!users?.some((u)=> u.id=== selectedUserId)){ 13setSelectedUserId(null)// 需要手动同步 15},[users, selectedUserId]) 17return[selectedUserId, selectedUserId]
Of course, whenever I see a useEffect
, especially one that calls setSate
inside it, I want to find a better solution. In my experience, there is almost always one, and it's usually worth pursuing it. So let's take a step back and try to find out what we want to achieve first.
当然,每当我看到 useEffect
,尤其是里面还调用了 setState
,我就想找个更好的方案。根据我的经验,几乎总能找到,而且通常值得去追寻。所以让我们退一步,先弄清楚我们到底想达成什么。
Keeping State in Sync
保持状态同步
In a nutshell, we want to keep our Client State - the selectedUserId
, in sync with our Server State - the list of users
. This makes sense: If a background refetch comes in from useQuery
, and the user was deleted from our list while we still have it stored in state, that selection becomes invalid.
简而言之,我们希望让客户端状态——selectedUserId
,与服务器状态——users
列表保持同步。这很合理:如果 useQuery
在后台重新获取数据,而用户被从列表中删除,但我们仍将其保存在状态中,那么该...