useCallback中如何获取最新值?myFood与可视项id匹配未打印如何修复
修复方案
核心原因
你的问题本质是useCallback闭包捕获了旧的myFood值,再加上viewabilityConfigCallbackPairs存储在useRef中未同步更新,导致FlatList一直调用绑定的旧版本回调函数,拿不到最新的myFood数组值。
修复步骤
1. 用useRef存储最新的myFood值(绕开闭包问题)
直接通过ref读取永远是最新的数组,不需要依赖useCallback的依赖项更新:
import { useRef, useEffect, useCallback } from 'react'; import { FlatList } from 'react-native'; // ...你的其他代码 const {myFood, loaduserhasMorePosts, loadPostsLoading} = useSelector( (state) => state.post, ); // 新增ref存储最新myFood const myFoodRef = useRef(myFood); // 每次myFood更新同步到ref useEffect(() => { myFoodRef.current = myFood; }, [myFood]); // 修复onViewableItemsChanged,从ref拿最新值 const onViewableItemsChanged = useCallback( async ({viewableItems}) => { // 新增调试日志,确认两个值的类型和内容 const lastFoodId = myFoodRef.current[myFoodRef.current.length - 1]?.id; const lastViewableId = viewableItems[viewableItems.length - 1]?.item?.id; console.log('对比值:', lastFoodId, lastViewableId, typeof lastFoodId, typeof lastViewableId); if (lastFoodId === lastViewableId) { console.log('success'); } }, [] // 不需要加myFood依赖,ref本身引用不变 ); // 如果用viewabilityConfigCallbackPairs,需要同步更新ref里的配置 const viewabilityConfigCallbackPairs = useRef([ { viewabilityConfig: { // 这里补你自己的可见性配置,比如itemVisiblePercentThreshold: 50 }, onViewableItemsChanged, } ]); // 每次onViewableItemsChanged更新,同步更新pairs useEffect(() => { viewabilityConfigCallbackPairs.current = [ { viewabilityConfig: { // 和上面的配置保持一致 }, onViewableItemsChanged, } ]; }, [onViewableItemsChanged]); return ( <> <FlatList viewabilityConfigCallbackPairs={viewabilityConfigCallbackPairs.current} data={myFood} // 如果你不需要多组可见性配置,更简单的写法是直接传两个prop,不用pairs: // viewabilityConfig={{你的配置}} // onViewableItemsChanged={onViewableItemsChanged} /> </> );
2. 检查Redux更新逻辑
确认你修改myFood数组时返回的是新数组引用,比如:
// 正确写法,返回新数组 case 'UPDATE_MY_FOOD': return { ...state, myFood: [...state.myFood, ...newFoodList] } // 错误写法,直接修改原数组,引用不变useSelector检测不到更新 case 'UPDATE_MY_FOOD': state.myFood.push(...newFoodList) return state
3. 排查类型问题
如果调试日志打印两个值看起来一样但===不相等,大概率是类型不同(比如一个是数字7,一个是字符串"7"),可以转成同类型再对比:
if (String(lastFoodId) === String(lastViewableId)) { console.log('success'); }
内容的提问来源于stack exchange,提问作者user15322469
相关产品推荐
相关产品推荐

