简体   繁体   English

反应钩子 - onClick 和 useEffect

[英]React hooks - onClick and useEffect

React Hooks is not updating to use the prop passed down and then stored. React Hooks 不会更新为使用传递下来然后存储的道具。 Usually I would resolve useState issues by calling functionality inside useEffect but in this case I need to update after a click event:通常我会通过调用 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)} />;

When clickHandler is called currentLayer state is undefined despite having been set earlier.当 clickHandler 被调用时 currentLayer state 未定义,尽管之前已设置。

What is the best way to combine useEffect and the clickHandler, or am I missing something else?将 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} />

}

I don't see a reason why you need the useEffect hook.我看不出你需要 useEffect 钩子的原因。 In fact, you should not set the currentLayer props in this component but rather use it as it is.实际上,您不应该在该组件中设置 currentLayer 属性,而应按原样使用它。 This is so that when there is a change in the props.currentLayer, this component will also re-render.这样当 props.currentLayer 发生变化时,该组件也会重新渲染。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM