React Native UseState 数组清除
React Native UseState Array Clear
我有以下代码 - 我的想法是创建一条动画多段线(用于地图)。我在互联网上找到了一些东西,但它是 "old" methods/without useEffect
, useState
...
我无法清除 else
中的 polylinePath
数组 - 我试图打印出当前长度,但它总是 returns 来自 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>
);
}
在使用效果中当你使用一个空数组作为依赖时它永远不会移动所以使用效果只会被调用一次(比如componentDidMount)。所以这里的使用效果要看Direction。
useEffect(() => {
const interval = setInterval(() => {
animatePolylineStart();
}, 70);
return () => clearInterval(interval);
}, [props.Direction]);
return useEffect 方法中的 setPolyLinePath([])
useEffect(() => {
return () => {
clearInterval(interval);
setPolyLinePath([])
};
}, []);
我有以下代码 - 我的想法是创建一条动画多段线(用于地图)。我在互联网上找到了一些东西,但它是 "old" methods/without useEffect
, useState
...
我无法清除 else
中的 polylinePath
数组 - 我试图打印出当前长度,但它总是 returns 来自 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>
);
}
在使用效果中当你使用一个空数组作为依赖时它永远不会移动所以使用效果只会被调用一次(比如componentDidMount)。所以这里的使用效果要看Direction。
useEffect(() => {
const interval = setInterval(() => {
animatePolylineStart();
}, 70);
return () => clearInterval(interval);
}, [props.Direction]);
return useEffect 方法中的 setPolyLinePath([])
useEffect(() => {
return () => {
clearInterval(interval);
setPolyLinePath([])
};
}, []);