【问题标题】:React Native useState not working inside of watchPositionAsyncReact Native useState 在 watchPositionAsync 内部不起作用
【发布时间】:2021-05-05 17:45:27
【问题描述】:

我正在尝试使用 React-Native-Maps 折线。但是,当用户四处移动时向数组添加新坐标时,我无法弄清楚我做错了什么。我的代码如下:

const Walk = () => {
    const [location, setLocation] = useState();
    const [coords, setCoords] = useState();
    const [last, setLast] = useState();
    const [watch, setWatch] = useState();
    const { onWalk, distance, setDistance, isPaused } = useContext(WalkContext);

    const getInitLocation = async () => {
        const { granted } = await Location.requestPermissionsAsync();
        if (!granted) return;

        const currentLocation = await Location.getCurrentPositionAsync({});
        setLocation(currentLocation.coords);

        const firstLast = {
            latitude: currentLocation.coords.latitude,
            longitude: currentLocation.coords.longitude
        };

        setLast(firstLast);
        setCoords([firstLast]);
    }

    const watchPosition = async () => {
        let newLoc;
        setWatch(
            newLoc =  await Location.watchPositionAsync({
                accuracy: Location.Accuracy.High,
                timeInterval: 1000000,
                distanceInterval: 100
            }, position => {
                const { latitude, longitude } = position.coords;
                const newCoord = {
                    latitude,
                    longitude
                }

                if (last) {
                    const newDist = distanceBetween(
                        last.latitude,
                        last.longitude,
                        newCoord.latitude,
                        newCoord.longitude
                    );
                    setDistance(distance + newDist);
                    setLast(newCoord);
                }

                const newCoords = [...coords, newCoord];
                setCoords(newCoords);
            
                setLocation(position.coords);
            }, 
            err => console.log(err))
        );
    }

    const stopWatching = () => {
        if (watch) {
            watch.remove();
        }
    }

    useEffect(() => {
        if (!location) {
            getInitLocation();
        }

        if (isPaused) {
            watchPosition();
        } else {
            stopWatching();
        }

    }, [isPaused]);
}

地图效果很好,只是我正在努力将新坐标正确添加到坐标状态。似乎它只将初始坐标和最后一个坐标添加到数组中。任何帮助表示赞赏。我确定这是一个简单的错误,但我无法弄清楚。

【问题讨论】:

  • 您是否在另一个 setState 函数中设置状态?

标签: reactjs react-native use-state react-native-maps


【解决方案1】:

嘿,您错误地使用了 setWatch() 它只接受需要返回数据的数据或函数 我可以看到你没有在 useWatch() 中返回任何东西

【讨论】:

    猜你喜欢
    • 2021-05-17
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多