首页 > 解决方案 > 反应传单 - MapContainer 仅获取父 useState 的初始值

问题描述

我有一个非常奇怪的场景使用react leaflet

我有一个父组件:

import React, { useEffect, useState, useRef} from "react";
import Locate from "locate";

export default function Chat (props) {

    const [allowLocation, setAllowLocation] = useState(true)


    function handleUpdate(p){
    console.log(allowLocation)
    if(allowLocation){
    console.log("update location")
    }

    }
    
    function handleShareLocation(){
    if(allowLocation){
        setAllowLocation(false)
    }else{
        setAllowLocation(true)
    }
    }

return(
<div>
  <button onClick={handleShareLocation}>share location</button>
  <Locate  parentUpdate={(p)=>{handleUpdate(p)}} />
</div>
)
}

基本上,父组件有一个allowLocation变量来控制用户是否允许向对方显示地图(它是一个聊天应用程序)。

Locate组件(子):

export default function Locate (props){
    
  function handleMarkerPosition(pos){
    props.parentUpdate(pos)
  }

  return(
  <div>
  <button onClick={e=>{handleMarkerPosition("test")}}>click test</button>
  <MapContainer 
    whenCreated={m => {mapRef.current = m}} center={[lat, lng]} zoom={16} scrollWheelZoom={false}>
    <TileLayer url="https://tiles.stadiamaps.com/tiles/alidade_smooth/{z}/{x}/{y}{r}.png"/>
    <DraggableMarker location={[lat, lng]} markerupdateposition={(pos)=>handleMarkerPosition(pos)} />
  </MapContainer>
  </div>
)}


 
function DraggableMarker(props) {
   ...
}
  1. 如果我单击click test按钮,它将调用handleMarkerPosition函数,该函数将调用,并从父组件props.parentUpdate触发。handleUpdate然后,它将根据allowLocation(这是预期的行为)触发

  2. 但是如果我使用相同的功能拖动DraggableMarker周围,handleMarkerPosition将始终从父级获取初始值allowLocation,无论我如何更改父级中的值。

为什么会这样?我只检查allowLocation父组件,但不知何故子组件总是记住其父组件的初始值。而且,12都共享同样的功能。

我该如何解决这个问题?

标签: javascriptreactjsreact-leaflet

解决方案


推荐阅读