React Hooks Error: Hooks can only be called inside the body of a function component

后端 未结 17 2133
旧巷少年郎
旧巷少年郎 2020-12-05 04:07

I am getting this error when using the useState hook. I have this in it\'s basic form, looking at the react docs for a reference, but am still getting this erro

17条回答
  •  我在风中等你
    2020-12-05 04:11

    I was able to solve this by importing React's primitive hooks in the component file, then passing them into my custom hooks. For some reason, the error only occurs when I import the React hook (like useState) in my custom hook file.

    I'm importing useState in my component file:

    import React, {useState} from 'react'; // import useState
    
    import {useCustomHook} from '../hooks/custom-hook'; // import custom hook
    
    const initialState = {items: []};
    export default function MyComponent(props) {
        const [state, actions] = useCustomHook(initialState, {useState});
        ...
    }
    

    Then in my hook file:

    // do not import useState here
    
    export function useCustomHook(initialValue, {useState}) {
        const [state, setState] = useState(initialValue || {items: []});
    
        const actions = {
            add: (item) => setState(currentState => {
                const newItems = currentState.items.concat([item]);
                return {
                    ...currentState,
                    items: newItems,
                };
            }),
        };
    
        return [state, actions];
    }
    

    This method has improved the testability of my hooks because I don't need to mock React's library to provide the primitive hooks. Instead, we can pass in a mock useState hook right into the custom hook's function. I think this improves code quality, as your custom hooks now have no coupling with the React library, allowing for more natural functional programming and testing.

提交回复
热议问题