【问题标题】:React Native UseState Array ClearReact Native UseState 数组清除
【发布时间】:2020-04-09 09:41:52
【问题描述】:

我有以下代码 - 想法是创建一条动画折线(用于地图)。我在互联网上找到了一些东西,但它是使用“旧”方法/没有useEffect、useState... 我无法清除else 中的polylinePath 数组 - 我试图打印出当前长度,但它总是从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>
      );
  }

【问题讨论】:

    标签: javascript reactjs react-native use-state


    【解决方案1】:

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

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

    【讨论】:

    • 它没有改变任何东西 - 仍然返回相同的长度。 setPolylinePath([]); console.log(polylinePath.length); 它不会渲染。
    • props.Direction 的值如何随时间变化?
    • props.Direction 完全没有变化,它是一个具有固定坐标的数组。 polylinePath 应该随着时间而改变,因此可以逐点渲染线。
    • #edit 如果我刷新(自动保存)大约 10 次,我可以看到这条线,然后当我继续刷新时,我可以为这条线设置动画。
    • 我认为你应该第一次从一个空数组开始:useState([]);所以它会进入 if polylinePath.length &lt; props.Direction.length
    【解决方案2】:

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

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

    【讨论】:

    • 我试过了 - 没有任何变化。仍然必须“自动保存重新加载”才能进行更改。没有动画。
    猜你喜欢
    • 2020-07-18
    • 2022-12-17
    • 2017-12-28
    • 2021-05-27
    • 1970-01-01
    • 2021-06-23
    • 2021-11-15
    • 1970-01-01
    • 2019-12-06
    相关资源
    最近更新 更多