如何将 return 的 React 钩子获取到组件中

How to get return of react hook into a component

根据 React,您只能在函数内部调用钩子。

但在某些时候,我想我会希望在调用该函数的组件中获得该挂钩的输出。

所以我正在尝试执行以下操作

class AreaOfInterestSelector extends Component<IProps> {
    render() {
        const areas: object = GetAreasOfInterest();
        console.log(areas);
        return <React.Fragment>
            {this.props.noSelectionMessage}
        </React.Fragment>
    }
}

const GetAreasOfInterest = () => {
    const [areas, setAreas] = useState({});
    const categoryApi = '//example.org/api/category';
    const getCategories = async () => {
        const data = await Axios.get(categoryApi);
        return data;
    }
    useEffect( () => {
        const data = getCategories();
        setAreas(data);
    });

    return areas;
}

export default GetAreasOfInterest;

但我最终收到错误

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

检查我的顶级依赖项我没有不匹配的版本或多个副本,在检查所有内容并查看之前我想我会问,因为我敢打赌我在这里犯了一个愚蠢的错误。

根据 React,您只能在函数 组件 中调用钩子。您在函数内部使用挂钩,而不是函数组件。

要成为一个组件,它应该 return 一个元素,并将其用作一个组件。所以它会像这样(考虑到你正在 returning 一个元素):

<GetAreasOfInterest/>