我知道这个问题已经被问了很多次,但我认为我的问题是不同的。我不想学习如何实现HOC,我已经做到了(虽然还没有测试:),我的问题是使用它。
下面是我的HOC
const withBaseFunctionality =
<T extends BaseModel, P extends BaseProps<T>>(
WrappedComponent: FunctionComponent<P>
) =>
(props: P) => {
//States
const [page, setPage] = useState(1);
//Update props
const updatedProps = produce(props, (draftProps) => {
draftProps.handlePageChange = handlePageChange;
draftProps.fetchItems = fetchItems;
draftProps.handleCreateItem = handleCreateItem;
draftProps.handleUpdateItem = handleUpdateItem;
draftProps.handleDeleteItem = handleDeleteItem;
});
//API
const fetchItems = useItems(props.subPath, page - 1);
//Handles all the create logic
const handleCreateItem = (item: T) => {};
//Handles all the update logic
const handleUpdateItem = (item: T) => {};
//Handles all the delete logic
const handleDeleteItem = (item: T) => {};
//Handles page changes
const handlePageChange = (page: number) => setPage(page);
return <WrappedComponent {...updatedProps} />;
};导出默认withBaseFunctionality;
以及我是如何尝试使用它的
interface TestModel extends BaseModel{
name: string;
acronym: string;
}
interface TestProps extends BaseProps<TestModel>{
}
const TestPage: FunctionComponent<TestProps> = ({}) => {
return<></>;
}
export default withBaseFunctionality(TestPage);我在这行export default withBaseFunctionality(TestPage);上得到了下面的错误
Argument of type 'FunctionComponent<TestProps>' is not assignable to parameter of type
'FunctionComponent<BaseProps<BaseModel>>'.
Types of property 'propTypes' are incompatible.
Type 'WeakValidationMap<TestProps> | undefined' is not assignable to type
'WeakValidationMap<BaseProps<BaseModel>> | undefined'.
Type 'WeakValidationMap<TestProps>' is not assignable to type
'WeakValidationMap<BaseProps<BaseModel>>'.
Types of property 'handleCreateItem' are incompatible.
Type 'Validator<(item: TestModel) => void> | undefined' is not assignable to type
'Validator<(item: BaseModel) => void> | undefined'.
Type 'Validator<(item: TestModel) => void>' is not assignable to type
'Validator<(item: BaseModel) => void>'.
Type '(item: TestModel) => void' is not assignable to type '(item: BaseModel) =>
void'.ts(2345)请注意,我不太擅长Typescript or JS,我正在使用我的Java知识。
发布于 2021-06-06 21:57:57
我过多地考虑了应用程序,我所需要做的就是像这样创建TestPage const TestPage = ({fetchItems}: TestProps) => {,然后所有的错误都消失了,事实上,甚至HOC中的逻辑也是有效的。
https://stackoverflow.com/questions/67859598
复制相似问题