1

我有以下代码 - 想法是创建一条动画折线(用于地图)。我在互联网上找到了一些东西,但它是使用“旧”方法/没有useEffectuseState......我无法清除polylinePath数组else- 我试图打印出当前长度,但它总是返回初始状态长度从props.Direction. 你能帮助我吗?我不知道为什么我的 AnimatedPolyline 不起作用。

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

export default function AnimatedPolyline(props) {
  const [polylinePath, setPolylinePath] = useState(props.Direction);

  useEffect(() => {
    const interval = setInterval(() => {
      animatePolylineStart();
   }, 70);
    return () => clearInterval(interval);
  }, [props.Direction]); //tried [], too

   const animatePolylineStart = () => {
      if (polylinePath.length < props.Direction.length) {
         const Direction = props.Direction;
         const polylinePathTemp = [
            ...Direction.slice(0, polylinePath.length - 1)
         ];

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

2 回答 2

0

在 useEffect 方法中返回 setPolyLinePath([])

  useEffect(() => {
    return () => {
       clearInterval(interval);
       setPolyLinePath([])
    };
  }, []);

于 2020-04-09T10:46:41.330 回答
0

在使用效果中,当您使用空数组作为依赖项时,它永远不会移动,因此只会调用一次使用效果(如 componentDidMount)。所以这里的使用效果应该取决于Direction。

useEffect(() => {
  const interval = setInterval(() => {
    animatePolylineStart();
 }, 70);
  return () => clearInterval(interval);
}, [props.Direction]);
于 2020-04-09T09:50:51.347 回答