React Native中useSelector结合useEffect触发无限循环问题咨询
问题原因
useSelector默认对比逻辑问题:useSelector默认使用严格相等(===)对比前后两次返回的结果,只要引用不同就会触发组件重渲染。你在useSelector内部调用map方法,每次执行都会返回一个全新的数组引用,哪怕数组内的分类数据完全没有变化,也会被判定为状态更新。- 循环触发链路:每次
categories引用变化触发重渲染后,useEffect检测到依赖categories更新就会执行setValues,setValues触发组件再次重渲染,又会生成新的categories数组引用,反过来再次触发useEffect,形成无限循环。 - 额外潜在问题:你当前代码中遍历的是
state.products.allIds,但取值是从state.categories.byId中取,这大概率是笔误,应该替换为state.categories.allIds,否则会出现大量未定义项,也可能引发异常更新。
解决方案
方案1:使用缓存选择器(推荐)
使用reselect库的createSelector创建带缓存的记忆化选择器,只有当依赖的categories.allIds或categories.byId真实发生变化时,才会重新计算生成数组,否则返回之前的缓存引用。
示例代码:
// 放在category相关的selector文件中 import { createSelector } from '@reduxjs/toolkit' // 也可以用独立的reselect库 import { AppState } from '@reducers/rootReducer' const selectAllCategories = createSelector( (state: AppState) => state.categories.allIds, (state: AppState) => state.categories.byId, (allIds, byId) => allIds.map(id => byId[id.toString()]) ) // 组件内使用 const categories = useSelector(selectAllCategories)
方案2:给useSelector传入浅层对比函数
直接使用react-redux自带的shallowEqual作为useSelector的第二个参数,改为浅层对比数组内每一项的引用,而不是对比数组本身的引用:
import { useSelector, shallowEqual } from 'react-redux' // 组件内使用 const categories = useSelector( (state: AppState) => state.categories.allIds.map((id) => state.categories.byId[id.toString()]), shallowEqual )
方案3:调整useEffect依赖
把数组转换逻辑移到useEffect内部,直接依赖allIds和byId两个原始状态切片,避免额外的引用对比问题:
// 先取原始状态切片 const categoryAllIds = useSelector((state: AppState) => state.categories.allIds) const categoryById = useSelector((state: AppState) => state.categories.byId) useEffect(() => { // 内部再做数组转换 const categories = categoryAllIds.map(id => categoryById[id.toString()]) setValues([{ id: 1 }]) console.log("logging") }, [categoryAllIds, categoryById])
内容的提问来源于stack exchange,提问作者Isaac Medina
相关产品推荐
相关产品推荐

