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

React Native useState数组清空失败,AnimatedPolyline动画失效求助

Fixing AnimatedPolyline Not Resetting Properly in React Native

Let’s break down what’s going wrong with your AnimatedPolyline component and fix it step by step:

Key Issues in Your Code

  1. Closure Trap in useEffect: The interval function inside useEffect captures the initial values of polylinePath and props.Direction. Even after state updates, it keeps using these stale values, which is why you’re stuck seeing the original path length instead of the updated state.
  2. Backwards Path Logic: Your slice(0, polylinePath.length - 1) is reducing the path length instead of growing it—this is the opposite of what you need for a "drawing" animation.
  3. Stale State Dependencies: You’re relying directly on the polylinePath variable in your update logic, which can be out of sync with React’s actual state due to batching.

Corrected Implementation

Here’s the fixed code with explanations:

import React, { useState, useEffect, Fragment } from 'react';
import { Polyline } from 'react-native-maps';

export default function AnimatedPolyline(props) {
  // Start with empty array to ensure animation begins from scratch
  const [polylinePath, setPolylinePath] = useState([]);

  useEffect(() => {
    // Reset path whenever the Direction prop changes
    setPolylinePath([]);
    
    const interval = setInterval(() => {
      animatePolylineStart();
    }, 70);

    // Clean up interval when component unmounts or Direction changes
    return () => clearInterval(interval);
  }, [props.Direction]);

  const animatePolylineStart = () => {
    // Use functional state update to get the latest state (avoids closure issues)
    setPolylinePath(prevPath => {
      if (prevPath.length < props.Direction.length) {
        // Incrementally add the next coordinate from the Direction prop
        return [...prevPath, props.Direction[prevPath.length]];
      } else {
        // Reset to empty array once the full path is drawn
        return [];
      }
    });
  };

  return (
    <Fragment>
      {polylinePath.length > 0 && (
        <Polyline 
          coordinates={polylinePath} 
          strokeColor="#484848" 
          strokeWidth={5} 
        />
      )}
    </Fragment>
  );
}

What Changed & Why

  • Initial State: Starting with an empty array ensures the animation always begins from the first point, whether the component mounts or the Direction prop updates.
  • Functional State Update: Using setPolylinePath(prevPath => ...) guarantees we work with the most recent state value, eliminating the stale closure problem from the interval.
  • Correct Path Growth: Instead of slicing, we append the next coordinate directly from props.Direction—this builds the path one point at a time, creating the desired "drawing" effect.
  • Prop Change Reset: When props.Direction updates, we immediately reset the path to empty, so the animation restarts with the new route.

Additional Tips

  • If you want the animation to run only once (not loop), you can clear the interval inside the functional update once prevPath.length matches props.Direction.length.
  • Adjust the 70 ms interval to speed up or slow down the animation to your preference.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 10:17:58