You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native FlatList删除动画报interpolate未定义错误如何解决

问题原因
  • 动画值容器未持久化:如果rowTranslateAnimatedValues直接定义在函数组件顶层,每次组件重渲染都会被重置为空对象,导致读取时找不到对应值
  • ref回调执行时机晚于渲染:Swipeable的ref赋值回调是在组件挂载完成后才执行的,而render阶段计算Animated.View样式时会先读取动画值,此时还未完成赋值,自然为undefined
  • 索引作为键的隐藏问题:删除条目后所有后续条目的索引会整体前移,会导致动画值和条目对应关系错乱
解决方案

第一步:持久化动画值容器

用useRef包裹动画值存储对象,避免重渲染时被重置:

import { useRef } from 'react';

// 动画值容器持久化
const rowTranslateAnimatedValues = useRef({});

第二步:渲染时提前初始化动画值

不要依赖ref回调赋值,在renderItem阶段就完成对应条目动画值的初始化,同时删除逻辑补充useNativeDriver配置(高度动画不支持原生驱动,避免警告):

// 删除逻辑调整
const removeItemById = (inventoryItemIndex) => {
  Animated.timing(rowTranslateAnimatedValues.current[inventoryItemIndex], {
    toValue: 0,
    duration: 200,
    useNativeDriver: false
  }).start(() => {
    // 先清理失效的动画值,再更新列表数据
    delete rowTranslateAnimatedValues.current[inventoryItemIndex];
    // 此处补充过滤inventoryData更新状态的逻辑
  });
};

// FlatList修改后代码
<FlatList
  data={inventoryData}
  renderItem={({ item, index }) => {
    // 渲染前提前初始化动画值,保证读取时一定存在
    if (!rowTranslateAnimatedValues.current[index]) {
      rowTranslateAnimatedValues.current[index] = new Animated.Value(1);
    }
    return (
      <Swipeable
        key={index + 5}
        onSwipeableRightOpen={() => closeRow(index)}
      >
        <Animated.View
          style={{
            height: rowTranslateAnimatedValues.current[index].interpolate({
              inputRange: [0, 1],
              outputRange: [0, 78],
            }),
          }}
        >
          <Layout level={theme === 'dark' ? '3' : '1'}>
            <InventoryItem item={item} />
          </Layout>
        </Animated.View>
      </Swipeable>
    )
  }}
  keyExtractor={(item, index) => index.toString()}
/>

可选优化

如果你的条目存在唯一ID(比如item.id),建议将动画值的存储键从索引替换为条目ID,避免删除条目后索引偏移导致的动画值对应错乱问题。

内容的提问来源于stack exchange,提问作者nick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 23:54:02