简体   繁体   中英

How to use react hooks in events

I have a custom hook that takes an item from my Redux store and dispatches it to another part of the of the store. The hook should fire whenever an item is dropped on an element.

Sample code:

const useDragged = () => {
    const draggedItem = useSelector((state) => state.draggedItem);
    const dispatch = useDispatch(); 
    dispatch(addItem(draggedItem));
}
//calling useDragged() here works

<MyComponent>
    <div ... onDrop={useDragged}> ... </div> //calling here crashes because I'm calling it from a function
</MyComponent>

I get that this Violate the rules of hooks because onDrop is a function call and hooks shouldn't be called inside functions - I just don't know the "right" way to implement a solution.

I also get that I could solve the specific issue by setting the value with event.dataTransfer.setData but I'm more interested in how I solve my general problem of hooks in event calls rather than the actual case here.

You can't use hooks inside a function. You can only use them inside the body of the functional component. You can get the variables from the state, wherever. So you need to do:

function ComponentExample(props){
  const draggedItem = useSelector((state) => state.draggedItem);
  const dispatch = useDispatch(); 

  const useDragged = () => {
    dispatch(addItem(draggedItem));
  }
}

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