[英]I can't set the state in my handler function
I'm trying to set a const of my state but it seems that don't work when a few days ago it worked.我正在尝试设置我的 state 的常量,但几天前它似乎不起作用。
I call the setter in a function like this:我这样调用 function 中的设置器:
const [activeMarker, setActiveMarker] = useState(null);
const handleActiveMarker = (marker) => {
if (marker === activeMarker) {
return;
}
setActiveMarker(marker);
console.log(marker, '--', activeMarker)
};
That is called in那叫在
{markers.map(({ id, latitud, longitud}) => (
<Marker
key={id}
position={{lat: latitud, lng: longitud}}
onClick={() => handleActiveMarker(id) }
/>
))}
The attribute markers is an array of markers and it's printed well in my map, but when I click, in console.log of my handler I get the id of marker and null in activeMarker where it has to appear the same number.属性标记是一个标记数组,它在我的 map 中打印得很好,但是当我单击时,在我的处理程序的 console.log 中,我得到标记的 id 和 activeMarker 中的null ,它必须显示相同的数字。
Remember useState is asynchronous so it will not update straight away.请记住 useState 是异步的,因此它不会立即更新。 To get the console.log value to log your value you should add a useEffect.
要获取 console.log 值以记录您的值,您应该添加一个 useEffect。
useEffect(() => {
console.log(activeMarker)
},[activeMarker])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.