“React has detected a change in the order of Hooks” but Hooks seem to be invoked in order

后端 未结 2 1490
梦谈多话
梦谈多话 2021-02-05 00:34

I am trying to use Context and Reducers via React\'s hooks, and running into problems with the order of the hooks not being constant. My understanding

相关标签:
2条回答
  • 2021-02-05 01:08

    I ran into this same error message in a component I was writing due to use of short-circuiting logic.

    This resulted in an error:

    const x = useSelector(state => state.foo);
    if (!x) { return ; }
    const y = useSelector(state => state.bar);
    
    

    This is because when x is truthy the list of hooks has length 2, but when x is falsey the list has length 1.

    To resolve the error I had to put all hook use before any early terminations.

    const x = useSelector(state => state.foo);
    const y = useSelector(state => state.bar);
    if (!x) { return ; }
    
    
    0 讨论(0)
  • 2021-02-05 01:13

    Writing my comment as an answer:

    The problem is that you're calling Event.Event() directly, even though it is a react component. That causes react to treat the hook calls inside the function as part of Container, even though you meant for them to be part of Event.

    The solution is to use JSX:

    return isTodays && <Event.Event dayHeight={dayHeight} event={e} />

    Why this works is clearer when you replace the JSX with the resulting JS code:

    return isTodays && React.createElement(Event.Event, { dayHeight, event: e })

    See https://reactjs.org/docs/react-api.html#createelement. You never want to call the function components directly, how react works is that you always hand a reference the component to react and let it call the function at the correct time.

    0 讨论(0)
提交回复
热议问题