简体   繁体   中英

React hooks - onClick and useEffect

React Hooks is not updating to use the prop passed down and then stored. Usually I would resolve useState issues by calling functionality inside useEffect but in this case I need to update after a click event:

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.

What is the best way to combine useEffect and the clickHandler, or am I missing something else?

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. In fact, you should not set the currentLayer props in this component but rather use it as it is. This is so that when there is a change in the props.currentLayer, this component will also re-render.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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