【发布时间】:2025-12-03 07:20:04
【问题描述】:
所以我正在学习反应,但我不是 javascript 粉丝,所以我使用的是打字稿。因此,我尝试输入内容,但似乎使用any 总是作弊出路。这是我的容器:
interface UserProfileRouteProps {
userId: string
}
export function mapStateToProps(state: StoreState, props: RouteComponentProps<UserProfileRouteProps>) {
let userId: number = parseInt(props.match.params.userId)
const user = state.users.find(u => u.id === userId)
return {
id: userId,
name: user.name,
foo: user.foo
}
}
export function mapDispatchToProps(dispatch: Dispatch<actions.UserProfileActions>, props: RouteComponentProps<UserProfileRouteProps>) {
let userId: number = parseInt(props.match.params.userId)
return {
onFoo: () => dispatch(actions.foo()),
onDelete: () => dispatch(actions.delete(recipeId))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(UserProfile as any)
这是组件
export interface UserProfileProps{
id: number
name: string
foo: IFoo
onFoo?: () => void
onDelete?: () => void
}
export class UserProfile extends React.Component<UserProfileProps, void>{
现在我希望我的mapStateToProps 和mapDispatchToProps 是强类型的,并且返回类型为UserProfileProps,但我不能这样做,因为connect() 抛出了一个错误:
error TS2345: Argument of type 'typeof UserProfile' is not assignable to parameter of type 'ComponentType<UserProfileProps & { onFoo: () => { type: string; }; onDelete: () => ...'
所以我在谷歌上搜索后的作弊是去UserProfile as any。
这里实际发生了什么?我这样做对吗?我应该有单独的容器道具和组件道具吗?我试图让组件不知道路由。
【问题讨论】:
标签: reactjs typescript react-redux