我正在尝试实现 HOC,它将根据用户是否获得授权将其重定向到指定路径
import {Navigate} from "react-router-dom";
import {useAppSelector} from "../redux/redux-store";
import React from "react";
export const withAuthNavigate = <Props extends JSX.IntrinsicAttributes>(
Component: React.ComponentType<Props>
) => (props: Props) => {
const isAuth = useAppSelector(state => state.authReducer.isAuth)
return isAuth ? <Component {...props}/> : <Navigate to="/login"/>
}
目标组件文件:
const mapStateToProps = (state: RootState) => {
return {
dialogs: state.dialogsReducer.dialogs,
messages: state.dialogsReducer.messages
}
}
const mapDispatchToProps = (dispatch: AppDispatch) => {
return {
sendMessage: (messageText: string) => {
dispatch(sendMessage(messageText))
}
}
}
const authNavigateComponent = withAuthNavigate(Dialogs)
const DialogsContainer = connect(mapStateToProps, mapDispatchToProps)(authNavigateComponent)
export default DialogsContainer;
错误:
`TS2345: Argument of type 'FC<DialogsProps>' is not assignable to
parameter of type 'ComponentType<IntrinsicAttributes>'. Type
'FunctionComponent<DialogsProps>' is not assignable
to type 'FunctionComponent<IntrinsicAttributes>'. Types of property
'propTypes' are incompatible. Type 'WeakValidationMap<DialogsProps> | undefined'
is not assignable to type
'WeakValidationMap<IntrinsicAttributes> | undefined'. Type
'WeakValidationMap<DialogsProps>' has no properties in common with
type 'WeakValidationMap<IntrinsicAttributes>'.`
我不太明白子组件应该有什么 props。
问题出在传递给目标组件Dialogs的道具中。原来是这样的:
type DialogsProps = {
dialogs: Array<{id: number, name: string}>,
messages: Array<{id: number, messageText: string}>,
sendMessage: (messageText: string) => void
}
我将其更改为减速器中使用的类型:
type DialogType = {
id: IdType,
name: string
} type MessageType = {
id: IdType,
messageText: string
}
type DialogsProps = {
dialogs: Array<DialogType>,
messages: Array<MessageType>,
sendMessage: (messageText: string) => void
}
还是没有完全明白问题的原因,不过已经解决了。