简体   繁体   English

React Native UseState 数组清除

[英]React Native UseState Array Clear

I have the following code - the idea is to create an animated polyline (for a map).我有以下代码 - 想法是创建一条动画折线(用于地图)。 I found some stuff in the internet, but it was with the "old" methods/without useEffect , useState ... I can´t clear the polylinePath array in the else - I am trying to print out the current length, but it always returns the initial state length from props.Direction .我在互联网上找到了一些东西,但它是使用“旧”方法/没有useEffectuseState ...我无法清除else中的polylinePath数组 - 我试图打印出当前长度,但它总是从props.Direction返回初始 state 长度。 Can you help me?你能帮助我吗? I have no idea why my AnimatedPolyline isn´t working.我不知道为什么我的 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>
      );
  }

in use effect when you use an empty array as a dependency it will never move so use effect will be called only one time (like componentDidMount).在使用效果中,当您使用空数组作为依赖项时,它永远不会移动,因此只会调用一次使用效果(如 componentDidMount)。 so here use effect should depend on Direction.所以这里的使用效果应该取决于Direction。

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM