我正在尝试将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 hook函数。
可能是因为它检测到homePage
永远不能用作组件-React组件以大写字母开头。小写将导致创建具有该名称的html元素,并且React将忽略您的组件。
当然,您稍后再包装它,但您的短绒棉不会将其考虑在内。所以给它起一个不同的名字,用一个大写的首字母。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句