React-Leaflet:无法从 React Context 动态创建折线

React-Leaflet: Cannot create a Polyline DYNAMICALLY from React Context

更新! 正如 Seth Luke 所问,为什么是 ref 而不是 state,所以我这样做了,现在画线了!但落后一步。查看这些行:

useEffect(()=>{
        if (drawing) {
                setZonePolygon((prev)=>[...prev, [clickLocation.lat, clickLocation.lng]]);
                setContextData((prevContext)=>({...prevContext, lines: zonePolygon}));
                addZoneMarker();
            }
        }, [clickLocation]);

上下文中的“lines”比本地状态“zonePolygon”更新了一步...我该如何更正这个问题?即使我切换呼叫,它也是一样的,上下文会延迟更新......

原创 POST:

我已连接到我的主地图组件中的上下文,其中包含一个 .我正在更改另一个组件的上下文,希望我的地图容器组件更新并重新呈现多段线,但它没有发生。我在这里做错了什么?我真的厌倦了阅读和尝试各种东西超过 15 个小时,现在没有休息。有人可以帮忙吗?非常感谢。

我的目标是让用户点击地图上的不同点并将它们连接成一条线,这样我就可以将其保存为一个区域或“区域”。

这没有被调用,我想知道为什么!我正在使用 React 开发工具进行调试,并且上下文确实得到了更改,但它没有在组件中触发......太奇怪了。

useEffect(()=>{
            console.log('Lines updated in Map component via Context.', lines);
        }, [lines]); // This is not being called, I wonder why!!! ****

这是我的代码:

import React, {useState, useEffect, useContext, useRef} from 'react';
import {MapContainer, Marker, Polyline, Polygon, useMapEvent} from 'react-leaflet';
import 'leaflet-rotatedmarker';
import {MapContext} from '../../context/MapProvider';
import Layers from './Layers';
import Ships from '../Ships';

const Map = () => {
    const [map, setMap] = useState(null);
    const {contextData, setContextData} = useContext(MapContext);
    const {clickLocation, drawing, lines} = contextData;
    const [shipData, setShipData] = useState();
        
    useEffect(()=>{
        console.log('Lines updated in Map component via Context.', lines);
    }, [lines]); // This is not being called, I wonder why!!! ****



    useEffect(()=>{
        if (!map) return;
        setContextData({...contextData, mapRef: map});
    }, [map]);

    useEffect(() => {
        setShipData(contextData.vessels);
    }, [contextData.vessels]);

    function MapEvents() {
        const map = useMapEvent('click', (e) => {
        setContextData({...contextData, clickLocation: e.latlng});
        });
        return null;
    }

    // const ZONE = [
    //  [-41.95208616893812, -73.52483926124243],
    //  [-42.246913395396184, -73.17047425039003],
    //  [-42.19905906325171, -72.68013196793146],
    //  [-41.936746304733255, -72.81473573174362],
    //  [-41.8118450173935, -73.22404105435608],
    // ]

    return (
        <MapContainer
                center={[-42, -73]} 
                zoom={10}   
                style={{height: '100%', width: '100%'}} 
                whenCreated={setMap}>
            <MapEvents />
            <Layers />      
            <Ships data={shipData} />
            {
                (drawing & lines.length > 1) ? <Polyline positions={lines} /> : null
            }
        </MapContainer>
    )
}

export default Map;

这是我修改上下文的地方:

import React, {useState, useEffect, useRef, useContext} from 'react';
import L from 'leaflet';
import styles from '../../styles.module.scss';
import ZoneItem from './ZoneItem';
import { MapContext } from './../../../../context/MapProvider';

const ZonesBar = () => {
    const {contextData, setContextData} = useContext(MapContext);
    const {mapRef, drawing, lines, clickLocation} = contextData;
    const [zones, setZones] = useState([]);
    const [zoneMarkers, setZoneMarkers] = useState([]);
    let zonePolygon = useRef([]);

    useEffect(()=>{
        if (drawing) {
            setContextData((contextData)=>({...contextData, lines: []}));
            zonePolygon.current = [];
        } else if (!drawing) {
            if (zonePolygon.current.length > 2) {
                setContextData((prevContext)=>({...prevContext, zones: [...prevContext.zones, contextData.lines]}));
                setZones((prevZones)=>([...prevZones, zonePolygon.current]));
                clearMarkers();
            }
        }
    }, [drawing]);

    useEffect(()=>{
        if (drawing) {
                zonePolygon.current.push([clickLocation.lat, clickLocation.lng]);
                setContextData((prevContext)=>({...prevContext, lines: zonePolygon.current}));
                addZoneMarker();
            }
        }, [clickLocation]);

    function toggleDrawing() {
        setContextData((prevContext)=>({...prevContext, drawing: !prevContext.drawing}))
    }

    function addZoneMarker() {
        const newMarker = L.marker([clickLocation.lat, clickLocation.lng])
            .addTo(mapRef);
        setZoneMarkers((prevMarkers)=>([...prevMarkers, newMarker]));
    }

    function clearMarkers() {
        zoneMarkers.forEach(m => mapRef.removeLayer(m));
    }

    return (
        <div className={styles.zones}>
            <button 
                className={`${styles.btn_add} ${drawing ? styles.btn_drawing : ''}`}
                onClick={toggleDrawing}
                >
                    {drawing ? 'Agregar zona' : 'Definir zona'}
            </button>
            <span style={{fontSize: '0.7rem', fontStyle: 'italic', marginLeft: '0.5rem',}}>
                {drawing ? 'Dar clicks en el mapa para definir la zona, luego presionar el botón otra vez.' : ''}
            </span>

            <div className={styles.list}>
            {
                    zones.length > 0 ?
                    zones.map(zone => <ZoneItem data={zone} />)
                    :
                    'Lista vacía.'
                }                       
            </div>
        </div>  
    )
}

export default ZonesBar;

从今天上午 9 点开始,我已经改变了很多东西,以至于我不知道其他任何事情了。显然有一种方法可以做到这一点,我确实需要一些帮助。如果你能花时间解决这个问题,那对我来说就是救命稻草。 这就是它的样子,看看当我用硬编码数组渲染它时,折线出现了。

这是我的上下文:

import React, {useState, useEffect, createContext, useContext} from 'react'
import io from 'socket.io-client'
import axios from 'axios';

export const MapContext = createContext();
const socket = io("http://localhost:3001");

const MapProvider = ({children}) => {
    const [contextData, setContextData] = useState({
        mapRef: null,
        clickLocation: [],
        markers: [],
        zones: [],
        drawing: false,
        lines: [],
        vessels: []
    });
    
    // Bring vessels info from API and store in Context.
    useEffect(()=>{
        axios.get('http://localhost:3001/vessel/search/all')
        .then(res => {
            setContextData((prevContext)=>({...prevContext, vessels: res.data}));
        })
        .then(()=>{
            socket.on('vessels', data => {
            setContextData((prevContext)=>({...prevContext, vessels: data}));
            })
        })
        .catch(err => console.log(err.message));
    }, []);

    return (
        <MapContext.Provider value={{contextData, setContextData}}>
            {children}
        </MapContext.Provider>
    )
}

export default MapProvider;

我看不出有什么异常。但是尝试将 MapEvents 移到 Map 组件之外。像

function MapEvents() {
   const {contextData, setContextData} = useContext(MapContext);

   const map = useMapEvent('click', (e) => {
       setContextData({...contextData, clickLocation: e.latlng});
     });

   return null;
}

const Map = () => {
    const [map, setMap] = useState(null);
    const {contextData, setContextData} = useContext(MapContext);
    const {clickLocation, drawing, lines} = contextData;
    const [shipData, setShipData] = useState();
    const linesForPolyline = useRef();

    useEffect(()=>{
        console.log('Lines updated in Map component via Context.', lines);
    }, [lines]);

    useEffect(()=>{
        if (!map) return;
        setContextData({...contextData, mapRef: map});
    }, [map]);

    useEffect(() => {
        setShipData(contextData.vessels);
    }, [contextData.vessels]);


    // const ZONE = [
    //  [-41.95208616893812, -73.52483926124243],
    //  [-42.246913395396184, -73.17047425039003],
    //  [-42.19905906325171, -72.68013196793146],
    //  [-41.936746304733255, -72.81473573174362],
    //  [-41.8118450173935, -73.22404105435608],
    // ]

    return (
        <MapContainer
                center={[-42, -73]} 
                zoom={10}   
                style={{height: '100%', width: '100%'}} 
                whenCreated={setMap}>
            <MapEvents />
            <Layers />      
            <Ships data={shipData} />
            {
                (drawing & lines.length > 1) ? <Polyline positions={lines} /> : null
            }
        </MapContainer>
    )
}

export default Map;

看起来 Seth Lutske 在对原始问题的评论中提出的建议加上一些调整就达到了目的。我希望他能 post 将其作为答案,以便我接受它作为解决方案。

基本上解决方案是使用状态挂钩:

const [zonePolygon, setZonePolygon] = useState([]);

而不是 useRef:

const zonePolygon = useRef();

然后为了让本地状态和全局上下文更新,我将它们分成不同的 useEffects。这是工作代码,但我认为它需要重构:

useEffect(()=>{
        if (drawing) {
            setZonePolygon((prev)=>[...prev, [clickLocation.lat, clickLocation.lng]]);
            addZoneMarker();
        }
    }, [clickLocation]);

    useEffect(()=>{
        setContextData((prevContext)=>({...prevContext, lines: zonePolygon}));
    }, [zoneMarkers]);