为什么我在 TypeScript 中使用 React Hook 时遇到“...既不是 React 函数组件也不是自定义 React Hook 函数”

Why I face with "... which is neither a React function component or a custom React Hook function" when I use React Hook in TypeScript

我正在尝试将 React 项目从 javascript 转换为 TypeScript。该项目是使用 CRA --typescript 创建的。我在其中使用 redux-saga。我没有 ts 编译错误,但遇到运行时错误。

我已经检查了 和其他一些人,我认为我没有违反上述规则。

import { IEventDto } from "dtos/event";
import React, { Dispatch, memo, useEffect } from "react";
import { connect } from "react-redux";
import { compose } from "redux";
import { createStructuredSelector } from "reselect";
import { useInjectReducer, useInjectSaga } from "utilities";
import { IGlobalState } from "utilities/iState";
import { loadNearByEvents } from "./actions";
import reducer from "./reducer";
import saga from "./saga";
import { selectEvents } from "./selector";

interface IProps {
    events: IEventDto[];
}

interface IDispatches {
    loadEvents: () => void;
}

// I also tested it with normall function instead of arrow function.
// function homePage(props: IProps & IDispatches): JSX.Element {
const homePage: React.FC<IProps & IDispatches> = (props) => {
    useInjectReducer({ key: "home", reducer });
    useInjectSaga({ key: "home", saga });

    // here is the issue
    useEffect(() => {
        props.loadEvents();
    }, []);

    return (<div>
        <h2>This is the home page</h2>
        {props.events.map((event) => (<div>{event.title}</div>))}
    </div>);
};

const mapStateToProps = createStructuredSelector<IGlobalState, IProps>({
    events: selectEvents(),
});

function mapDispatchToProps(dispatch: Dispatch<any>): IDispatches {
    return {
        loadEvents: () => dispatch(loadNearByEvents()),
    };
}

const withConnect = connect(
    mapStateToProps,
    mapDispatchToProps,
);

const HomePage = compose<React.FC>(
    withConnect,
    memo,
)(homePage);

export { HomePage };

错误信息是:

Line 23:5:  React Hook "useInjectReducer" is called in function "homePage: React.FC<IProps & IDispatches>" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks
Line 24:5:  React Hook "useInjectSaga" is called in function "homePage: React.FC<IProps & IDispatches>" which is neither a React function component or a custom React Hook function     react-hooks/rules-of-hooks
Line 26:5:  React Hook "useEffect" is called in function "homePage: React.FC<IProps & IDispatches>" which is neither a React function component or a custom React Hook function         react-hooks/rules-of-hooks

inject 方法是自定义 React 挂钩函数。

可能,因为它检测到 homePage 永远不能用作组件 - React 组件以大写字母开头。小写会导致 html 个具有该名称的元素被创建,你的组件将被 React 忽略。

当然,您稍后会包装它,但您的 linter 不会考虑到这一点。所以给它一个不同的名字,首字母大写。