Zustand selector 发生 infinate loops的原因以及解决

Zustand selector 发生 infinate loops

做zustand tutorial project的时候,使用选择器方法引入store,出现Maximum update depth exceeded,也就是组件一直重新渲染,改成直接使用store就没有不会出现这个问题。如下:

js 复制代码
  // const [xIsNext, setXIsNext] = useGameStore((state) => [
  //   state.xIsNext,
  //   state.setXIsNext,
  // ]);
  
  const { history, setHistory, xIsNext, setXIsNext } = useGameStore()

目前看到有关这个问题的博客很少,特此记录一下。

感谢一下我的mentor们,如此认真地教我,给我充足的时间学习

问题产生原因

官方文档的解释如下:

文档链接

也就是说,这是因为Zustand v5的改动,当selector返回一个新的引用,可能导致无限循环

细究了一下,问题产生原因如下:

  1. react的默认比较为引用比较,在zustandV5中沿用了这种方式。
  2. 每次重新渲染,useStore都会再执行一次,selector每次都返回的是一个新的引用
  3. zustand使用浅比较判断状态变化,触发重新渲染,以此往复

比如像下面这样使用selector

js 复制代码
  const { history, setHistory} = useGameStore(((state) => ({
    history: state.history,
    setHistory: state.setHistory,
  })));
  const [searchValue, setSearchValue] = useStore((state) 
          => [  state.searchValue,  state.setSearchValue,])

以上两种方法selector分别返回一个对象和一个数组,每次重新渲染,其引用都会发生变化,也就触发了infinate loops

解决方法

  1. 避免在selector中返回对象
    这是我认为最直接的办法:
js 复制代码
const history = useGameStore((state) => state.history);
const setHistory = useGameStore((state) => state.setHistory);
//不要像下面这样
//  const { history, setHistory} = useGameStore(((state) => ({
//    history: state.history,
//    setHistory: state.setHistory,
//  })));
  1. 采用文档中介绍的使用useShllow解决:
    但是useShllow比较对象只会比较最浅层的值,要注意可能产生的副作用
js 复制代码
  const { history, setHistory, xIsNext, setXIsNext } = useGameStore(useShallow((state) => ({
    history: state.history,
    setHistory: state.setHistory,
    xIsNext: state.xIsNext,
    setXIsNext: state.setXIsNext,
  })));

附: zustand实现原理

zustand源代码中useShallow实现部分如下(也就是比较值而非比较引用):

js 复制代码
import React from 'react'
import { shallow } from '../vanilla/shallow.ts'

export function useShallow<S, U>(selector: (state: S) => U): (state: S) => U {
  const prev = React.useRef<U>(undefined)
  return (state) => {
    const next = selector(state)
    return shallow(prev.current, next)
      ? (prev.current as U)
      : (prev.current = next)
  }
}
相关推荐
wen's19 分钟前
React Native 0.79.4 中 [RCTView setColor:] 崩溃问题完整解决方案
javascript·react native·react.js
vvilkim1 小时前
Electron 自动更新机制详解:实现无缝应用升级
前端·javascript·electron
vvilkim1 小时前
Electron 应用中的内容安全策略 (CSP) 全面指南
前端·javascript·electron
aha-凯心1 小时前
vben 之 axios 封装
前端·javascript·学习
漫谈网络1 小时前
WebSocket 在前后端的完整使用流程
javascript·python·websocket
失落的多巴胺3 小时前
使用deepseek制作“喝什么奶茶”随机抽签小网页
javascript·css·css3·html5
DataGear3 小时前
如何在DataGear 5.4.1 中快速制作SQL服务端分页的数据表格看板
javascript·数据库·sql·信息可视化·数据分析·echarts·数据可视化
影子信息3 小时前
vue 前端动态导入文件 import.meta.glob
前端·javascript·vue.js
样子20183 小时前
Vue3 之dialog弹框简单制作
前端·javascript·vue.js·前端框架·ecmascript
kevin_水滴石穿3 小时前
Vue 中报错 TypeError: crypto$2.getRandomValues is not a function
前端·javascript·vue.js