反应传单标记标题未更新

问题描述 投票:0回答:2

[我正在尝试动态更新标记的标题(当鼠标悬停在...上时工具提示内容...,但是该字段停留在初始化时的位置。

这是一个简化的测试用例:

// @flow
import {
    Box, Button
} from '@material-ui/core'
import React, { useState } from 'react';
import { Map, TileLayer, Marker } from 'react-leaflet'
import "leaflet/dist/leaflet.css"
import L from 'leaflet';
import icon from 'leaflet/dist/images/marker-icon.png';

let DefaultIcon = L.icon({ iconUrl: icon });
L.Marker.prototype.options.icon = DefaultIcon;

function Test(props) {
    const [mstate, setMstate] = useState(false)
    const [mlong, setMlong] = useState(13)
    // let mlong = (mstate) ? 13.047 : 13

    const flipMstate = () => {
        setMstate(!mstate)
        setMlong((mstate)? 13 : 13.047)
    }

    return (
        <Box component='div' style={{ width: '80%', height: '80%', position: 'relative', }}>
            <Button onClick={flipMstate} style={{ height: '10%' }} >
                Change marker
            </Button>
            <Map
                preferCanvas={true}
                style={{ height: '90%' }}
                center={[50.63, 13.047]}
                zoom={13}
                minZoom={3}
                maxZoom={18}
            >
                <TileLayer
                    attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?"
                />
                <Marker
                    title={mlong}
                    position={[50.63, mlong]}
                />
            </Map>
        </Box>
    )
}

export default Test

单击按钮时,标记将按其应有的方式移动。但是,如果将鼠标悬停在标记上,工具提示将始终显示“ 13”。查看调试器会显示“标题”字段已正确更新。如果我修改代码以在其他状态下启动,则工具提示显示将始终为13.047

我做错什么了吗?

reactjs leaflet react-leaflet
2个回答
0
投票

useState挂钩的设置者不会立即更改您的值。因此,当您呼叫setMlong((mstate)? 13 : 13.047)时,您使用的不是更新的mstate值,而是旧的。

尝试在其中添加useEffect钩并处理依赖状态:

useEffect(() => {
    setMlong((mstate)? 13 : 13.047)
}, [mstate]);

或查看其他解决方案来回答这个问题:

useState set method not reflecting change immediately


0
投票

使用react-leaflet的Tooltip实现所需的行为

 <Marker position={[50.63, mlong]}>
     <Tooltip direction="top" offset={[10, 0]}>
       {mlong}
     </Tooltip>
 </Marker>

Demo

© www.soinside.com 2019 - 2024. All rights reserved.