Uncaught Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement in React Hooks

前端 未结 4 1562
暖寄归人
暖寄归人 2021-01-07 18:06

Given the following component, when I press down on the age selector and change the value to 15, such that I render a form without the driver license field, I get the error:

4条回答
  •  爱一瞬间的悲伤
    2021-01-07 18:33

    So I also experienced this error, but it was not related to the hook being wrapped in a condition. Instead it was caused by me having bad key values.

    I had a component that moved items from one list to another by dragging and dropping. However, some of those items were locked, so I simply removed the reference to my hook in those elements.

    The issue was that I used the index as a key, thus when I dragged a new element on top it got the same key as the locked element, the value of ref was changed and React complained with the above error.

    So my answer to those who come across this issue is - check whether you have truly unique keys!

提交回复
热议问题