【发布时间】:2019-08-22 18:24:01
【问题描述】:
下面的示例是一个简化的摘录,其中子组件根据鼠标行为发出事件。 React 然后应该根据发出的事件更新 DOM。
function SimpleSample() {
const [addons, setAddons] = React.useState<any>({
google: new GoogleMapsTile('google'),
})
const [tooltip, setTooltip] = React.useState<null | { text: string[]; x; y }>(null)
React.useEffect(() => {
// ...
}, [])
const mapEventHandle = React.useCallback(
(event: MapEvents) => {
console.log('event', event.type, tooltip) // LOG 1
if (event.type === MapEventType.mouseoverPopup_show) {
setTooltip({ text: event.text, x: event.coordinates[0], y: event.coordinates[1] })
} else if (event.type === MapEventType.mouseoverPopup_move) {
if (tooltip) setTooltip({ ...tooltip, x: event.coordinates[0], y: event.coordinates[1] })
} else if (event.type === MapEventType.mouseoverPopup_hide) {
setTooltip(null)
}
},
[tooltip]
)
console.log('render', tooltip) // LOG 2
return <MapComponent addons={addons} onEvent={mapEventHandle} />
}
预期的事件顺序如下:
-
发出
mouseoverPopup_show,然后tooltip从null变为值,发生重新渲染 -
mouseoverPopup_move被发射,然后tooltip被更新,触发重新渲染
实际发生了什么:
- Logpoint
LOG 2记录tooltip的更新值(正确) - 当再次调用
mapEventHandle时,该闭包内的tooltip的值(日志点LOG 1)永远不会更新,始终为null。
我错过了什么吗?用错了钩子?
这是一个代码框
https://codesandbox.io/s/blissful-torvalds-wm27f
编辑:解码箱示例 setTooltip 甚至没有触发重新渲染
【问题讨论】:
-
这是有效的:codesandbox.io/s/inspiring-gauss-bnvdc。我刚刚从代码中删除了
event.coordinates,因为它不会在您的示例中定义(这些事件不是实际的鼠标事件)。 -
哦,只是查看codeandbox的控制台而不是浏览器控制台就被骗了,是的,它正在工作......好吧,这个错误是在创建示例时引入的。我要仔细看看源...
标签: reactjs typescript react-hooks