当我在TypeScript中使用React Hook时,为什么要面对“……既不是React函数组件也不是自定义的React Hook函数”

问题描述 投票:0回答:1

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

我已经检查了this question和其他几个,并且我认为我没有违反所提到的规则。

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方法是自定义反应挂钩函数。

reactjs typescript redux react-hooks redux-saga
1个回答
1
投票

类似,因为它检测到homePage永远不能用作组件-React组件以大写字母开头。小写字母将导致使用该名称创建html元素,并且React将忽略您的组件。

当然,您稍后再包装它,但您的短绒棉不会考虑这一点。因此,请给它一个不同的名称,并使用大写首字母。

© www.soinside.com 2019 - 2024. All rights reserved.