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

时间:2019-12-05 17:21:00

标签: reactjs typescript redux react-hooks redux-saga

我正在尝试将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方法是自定义反应挂钩函数。

1 个答案:

答案 0 :(得分:1)

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

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