所以我有一个 React 状态变量 const [pickingHotspot, setPickingHotspot] = useState(false);
。然后我有这个按钮 <button type="button" className="btn btn-outline-danger" onClick={() => setPickingHotspot(true)}>
,它只是将状态设置为 true onClick。我有另一个处理程序
tmp.on('mousedown', (event) => {
if (pickingHotspot){
console.log(tmp.mouseEventToCoords(event));
} else {
console.log(pickingHotspot);
}
});
其中 tmp
是 Pannellum 360 图像查看器(它是第三方库,但我认为它是什么并不重要),这在我的 useState(...,[])
中设置,它运行一次加载。最后,我有一个 onClick div,它只打印 pickingHotspot
的值以进行调试。这是奇怪的部分:
当我加载页面并单击调试div时,该值为false。很酷,那行得通。然后我单击按钮(应该将其设置为 true!),然后再次单击调试 div。价值是真实的!但是当我单击 Pannellum 查看器时,该值为 false?我不确定该值如何可能同时为真和假,具体取决于我点击的位置。这些变量是否有不同的版本/实例?我已经尝试将所有内容链接到 html 组件之外和 useEffect 之外的单个函数处理程序,以防发生一些奇怪的作用域问题,但到目前为止没有任何效果。
我试图展示所有需要的代码,但这里是完整的(我去掉了大部分不相关的东西来简化它,它有很多代码需要浏览。):
function TourCreator(props){
const [scenes, setScenes] = useState({});
const [media, setMedia] = useState({});
const [viewer, setViewer] = useState(null);
// Editor states
const [pickingHotspot, setPickingHotspot] = useState(false);
function handle(event){
if (pickingHotspot){
console.log(viewer.mouseEventToCoords(event));
} else {
console.log(pickingHotspot);
}
}
// Called once on load
useEffect(() => {
if (Object.keys(media).length == 0){
// Sends the request to the backend for "data"
sendGetRequest(window.$PROJECT, true, {
id: params["project_id"],
}).then((data) => {
data.images = reshapeArray(data.images, 3);
console.log(data)
setMedia(data);
let tmp = window.pannellum.viewer('panorama', tour)
setViewer(tmp);
// Print Pitch/Yaw on click
tmp.on('mousedown', (event) => handle(event));
});
}
}, [])
return (
<div className="p-3">
{/* MAIN CONTENT */}
<div className='tour-creator-root mx-auto p-3 row rounded'>
{/* MAIN BOX */}
<div className='main-box col-9 px-0 rounded'>
{/* Pannellum viewer */}
<div id='panorama' className="w-100 rounded-top">
<button type="button" className="save-button btn btn-outline-danger">
Save
</button>
</div>
{/* Toolbar */}
<div className="toolbar w-100 d-flex flex-column justify-content-center rounded-bottom p-3"
onClick={
() => {
console.log(pickingHotspot)
}
}>
<div className="d-flex flex-row justify-content-around">
<button type="button" className="btn btn-outline-danger" onClick={
() => setPickingHotspot(true)
}>
Add Hotspot
</button>
</div>
</div>
</div>
</div>
</div>
)
}
export default TourCreator;
答案 0 :(得分:1)
尝试在你的依赖数组中传递 pickHotspot 以使用 useEffect。
您的事件处理程序附加到 componentDidMount 上 useEffect 中的元素,因为依赖项数组为空。这只会发生一次,并且将使用旧功能。那个旧函数将 close 覆盖前一个状态的值。通过在 dependency array 中传递 pickHotSpot,您可以在每次相关状态更改时再次附加您的事件处理程序。
将所有相关代码保存在钩子中也是一种推荐的方法。您可以将侦听器函数放在钩子中,并且会看到来自您的 lint 工具之一的缺失依赖项警告。
此外,如果您没有特别的理由从 javascript 添加这样的事件处理程序,那么请在 JSX 中添加内联使用,就像建议的 @MB__ 一样。这将在每次渲染时执行,因此它应该是正确的。在任何时候都只会附加一个特定事件的事件处理程序。