简体   繁体   中英

useEffect does not get correct value

I am implementing a feature where the dropdown menu closes on tab/blur and automatically selects the highlighted item.

The component is structured in a way where the parent component renders it. When the dropdown component closes, it passes a callback to the parent which unmounts the dropdown component.

The issue is that the dropdown component itself does not know when the user closes it. The parent controls that state.

I would like to find a way to tell the parent component which item is currently highlighted so the parent can set that value. Only the dropdown component knows which item is currently highlighted.

I tried to add a callback to useEffect :

const [index, setIndex] = React.useState(0);

React.useEffect(() => {
  return () => {
    props.onSelect(items[index])
  }
}, [])

This doesn't seem to work. It looks like useEffect is created on mount and does not hold the current state of the index. It seems that the index is always 0 .

I would like a way to fire this onSelect function on unmount while saving the index state. Maybe something like this:

React.useEffect(() => {
  () => {
    props.onSelect(items[index]);
  }
}, [index]

The issue here is that whenever index changes, it calls onSelect , which closes the dropdown menu.

I would like the first useEffect to work while saving the index. Or somehow have the second useEffect to run only when the component unmounts.

How can I achieve this?

The effect captured a stale value.

This is documented in the React Hooks FAQ and there's a handy hook called useLatest in the react-use library that'll help with this.

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