React hooks - onClick and useEffect



React Hooks 没有更新以使用传递然后存储的 prop。通常我会通过在 useEffect 中调用功能来解决 useState 问题,但在这种情况下,我需要在单击事件后进行更新:

const [currentLayer, setCurrentLayer] = useState();
useEffect(() => {
console.log(props.currentLayer) // props.currentLayer is defined
setCurrentLayer(props.currentLayer);
}, [props.currentLayer]);
useEffect(() => {
console.log(currentLayer); // currentLayer state is defined
}, [currentLayer]);
/*
* Called when the timeline product is clicked
*/
const clickHandler = e => {
console.log(currentLayer); // currentLayer state is undefined
currentLayer.getSource().updateParams({ TIME: e.time });
};
return <Timeline options={props.timelineOptions} items={items} clickHandler={e => clickHandler(e)} />;

当 clickHandler 被称为 currentLayer 状态时,尽管之前已经设置过,但状态是未定义的。

结合useEffect和clickHandler的最佳方法是什么,还是我错过了其他东西?

import React from 'react'
const Component = (props) => {
// ... your other logic
const [currentLayer, setCurrentLayer] = useState(props.currentLayer)
const clickHandler = e => {
currentLayer.getSource().updateParams({ TIME: e.time });
}
return <Timeline options={props.timelineOptions} items={items} clickHandler={clickHandler} />
}

我看不出你需要useEffect钩子的原因。实际上,您不应该在此组件中设置currentLayer props,而应按原样使用它。这样,当 props.currentLayer 发生变化时,该组件也会重新渲染。

const clickHandler = e => {
props.currentLayer.getSource().updateParams({ TIME: e.time });
};

最新更新