javascript - 反应传单 - 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) {
...
}
如果我单击
click test
按钮,它将调用handleMarkerPosition
函数,该函数将调用,并从父组件props.parentUpdate
触发。handleUpdate
然后,它将根据allowLocation
(这是预期的行为)触发但是如果我使用相同的功能拖动
DraggableMarker
周围,handleMarkerPosition
将始终从父级获取初始值allowLocation
,无论我如何更改父级中的值。
为什么会这样?我只检查allowLocation
父组件,但不知何故子组件总是记住其父组件的初始值。而且,1
和2
都共享同样的功能。
我该如何解决这个问题?
解决方案
推荐阅读
- sql - 单词“FOR”附近的无效语法(但没有 FOR)
- sql - "with" 公用表表达式
- sql - sqlite 删除 a 列和 b 列不在前 n 项中的所有结果
- python - 为什么 tf 操作仅在任意函数中有效?
- sql - 如何使用 union all 处理多个 select 语句
- javascript - 使用文件调用 api 时出现验证错误
- android - Android-更改cardview背景颜色解析json
- android - 如何检测前置摄像头是否在android中可用?
- php - 根据 Woocommerce 中的运输类别有条件地设置运输成本
- xcode - 在 Mac 上启动 Jenkins 本地服务器